This repository was archived by the owner on May 30, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathgoogle_map.state.dart
More file actions
552 lines (475 loc) · 14.8 KB
/
Copy pathgoogle_map.state.dart
File metadata and controls
552 lines (475 loc) · 14.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
// Copyright (c) 2020, the MarchDev Toolkit project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'package:flutter/widgets.dart';
import 'package:flinq/flinq.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:google_directions_api/google_directions_api.dart';
import 'utils.dart';
import '../core/utils.dart' as utils;
import '../core/google_map.dart' as gmap;
import '../core/map_items.dart' as items;
class GoogleMapState extends gmap.GoogleMapStateBase {
final directionsService = DirectionsService();
final _markers = <String, Marker>{};
final _polygons = <String, Polygon>{};
final _polylines = <String, Polyline>{};
final _directionMarkerCoords = <GeoCoord, dynamic>{};
final _waitUntilReadyCompleter = Completer<Null>();
GoogleMapController _controller;
void _setState(VoidCallback fn) {
if (mounted) {
setState(fn);
} else {
fn();
}
}
FutureOr<BitmapDescriptor> _getBmpDesc(String image) async {
if (image == null) return BitmapDescriptor.defaultMarker;
if (utils.ByteString.isByteString(image)) {
return BitmapDescriptor.fromBytes(utils.ByteString.fromString(image));
}
return await BitmapDescriptor.fromAssetImage(
createLocalImageConfiguration(context),
image,
);
}
@override
void moveCameraBounds(
GeoCoordBounds newBounds, {
double padding = 0,
bool animated = true,
bool waitUntilReady = true,
}) async {
assert(() {
if (newBounds == null) {
throw ArgumentError.notNull('newBounds');
}
return true;
}());
if (waitUntilReady == true) {
await _waitUntilReadyCompleter.future;
}
if (animated == true) {
await _controller?.animateCamera(CameraUpdate.newLatLngBounds(
newBounds.toLatLngBounds(),
padding ?? 0,
));
} else {
await _controller?.moveCamera(CameraUpdate.newLatLngBounds(
newBounds.toLatLngBounds(),
padding ?? 0,
));
}
}
@override
void moveCamera(
GeoCoord latLng, {
bool animated = true,
bool waitUntilReady = true,
double zoom,
}) async {
assert(() {
if (latLng == null) {
throw ArgumentError.notNull('latLng');
}
return true;
}());
if (waitUntilReady == true) {
await _waitUntilReadyCompleter.future;
}
if (animated == true) {
await _controller?.animateCamera(CameraUpdate.newLatLngZoom(
latLng.toLatLng(),
zoom ?? await _controller?.getZoomLevel(),
));
} else {
await _controller?.moveCamera(CameraUpdate.newLatLngZoom(
latLng.toLatLng(),
zoom ?? await _controller?.getZoomLevel(),
));
}
}
@override
void zoomCamera(
double zoom, {
bool animated = true,
bool waitUntilReady = true,
}) async {
assert(() {
if (zoom == null) {
throw ArgumentError.notNull('zoom');
}
return true;
}());
if (waitUntilReady == true) {
await _waitUntilReadyCompleter.future;
}
if (animated == true) {
await _controller?.animateCamera(CameraUpdate.zoomTo(zoom));
} else {
await _controller?.moveCamera(CameraUpdate.zoomTo(zoom));
}
}
FutureOr<GeoCoord> get center async =>
(await _controller?.getVisibleRegion())?.toGeoCoordBounds()?.center;
FutureOr<double> get zoom async =>
(await _controller?.getZoomLevel());
FutureOr<GeoCoordBounds> get bounds async => (await _controller?.getVisibleRegion()).toGeoCoordBounds();
@override
void changeMapStyle(
String mapStyle, {
bool waitUntilReady = true,
}) async {
if (waitUntilReady == true) {
await _waitUntilReadyCompleter.future;
}
try {
await _controller?.setMapStyle(mapStyle);
} on MapStyleException catch (e) {
throw utils.MapStyleException(e.cause);
}
}
@override
void addMarkerRaw(
GeoCoord position, {
String label,
String icon,
String info,
String infoSnippet,
ValueChanged<String> onTap,
VoidCallback onInfoWindowTap,
}) async {
assert(() {
if (position == null) {
throw ArgumentError.notNull('position');
}
if (position.latitude == null || position.longitude == null) {
throw ArgumentError.notNull('position.latitude && position.longitude');
}
return true;
}());
final key = position.toString();
if (_markers.containsKey(key)) return;
final markerId = MarkerId(key);
final marker = Marker(
markerId: markerId,
onTap: onTap != null ? () => onTap(key) : null,
consumeTapEvents: onTap != null,
position: position.toLatLng(),
icon: icon == null
? BitmapDescriptor.defaultMarker
: await _getBmpDesc('${fixAssetPath(icon)}$icon'),
infoWindow: info != null
? InfoWindow(
title: info,
snippet: infoSnippet,
onTap: onInfoWindowTap,
)
: null,
);
_setState(() => _markers[key] = marker);
}
@override
void addMarker(items.Marker marker) => addMarkerRaw(
marker.position,
label: marker.label,
icon: marker.icon,
info: marker.info,
infoSnippet: marker.infoSnippet,
onTap: marker.onTap,
onInfoWindowTap: marker.onInfoWindowTap,
);
@override
void removeMarker(GeoCoord position) {
assert(() {
if (position == null) {
throw ArgumentError.notNull('position');
}
if (position.latitude == null || position.longitude == null) {
throw ArgumentError.notNull('position.latitude && position.longitude');
}
return true;
}());
final key = position.toString();
if (!_markers.containsKey(key)) return;
_setState(() => _markers.remove(key));
}
@override
void clearMarkers() => _setState(() => _markers.clear());
@override
void addDirection(
dynamic origin,
dynamic destination, {
String startLabel,
String startIcon,
String startInfo,
String endLabel,
String endIcon,
String endInfo,
}) {
assert(() {
if (origin == null) {
throw ArgumentError.notNull('origin');
}
if (destination == null) {
throw ArgumentError.notNull('destination');
}
return true;
}());
final request = DirectionsRequest(
origin: origin is GeoCoord
? LatLng(origin.latitude, origin.longitude)
: origin,
destination:
destination is GeoCoord ? destination.toLatLng() : destination,
travelMode: TravelMode.driving,
);
directionsService.route(
request,
(response, status) {
if (status == DirectionsStatus.ok) {
final key = '${origin}_$destination';
if (_polylines.containsKey(key)) return;
moveCameraBounds(
response?.routes?.firstOrNull?.bounds,
padding: 80,
);
final leg = response?.routes?.firstOrNull?.legs?.firstOrNull;
final startLatLng = leg?.startLocation;
if (startLatLng != null) {
_directionMarkerCoords[startLatLng] = origin;
if (startIcon != null || startInfo != null || startLabel != null) {
addMarkerRaw(
startLatLng,
icon: startIcon ?? 'assets/images/marker_a.png',
info: startInfo ?? leg.startAddress,
label: startLabel,
);
} else {
addMarkerRaw(
startLatLng,
icon: 'assets/images/marker_a.png',
info: leg.startAddress,
);
}
}
final endLatLng = leg?.endLocation;
if (endLatLng != null) {
_directionMarkerCoords[endLatLng] = destination;
if (endIcon != null || endInfo != null || endLabel != null) {
addMarkerRaw(
endLatLng,
icon: endIcon ?? 'assets/images/marker_b.png',
info: endInfo ?? leg.endAddress,
label: endLabel,
);
} else {
addMarkerRaw(
endLatLng,
icon: 'assets/images/marker_b.png',
info: leg.endAddress,
);
}
}
final polylineId = PolylineId(key);
final polyline = Polyline(
polylineId: polylineId,
points: response?.routes?.firstOrNull?.overviewPath
?.mapList((_) => _.toLatLng()) ??
[startLatLng?.toLatLng(), endLatLng?.toLatLng()],
color: const Color(0xcc2196F3),
startCap: Cap.roundCap,
endCap: Cap.roundCap,
width: 8,
);
_setState(() => _polylines[key] = polyline);
}
},
);
}
@override
void removeDirection(dynamic origin, dynamic destination) {
assert(() {
if (origin == null) {
throw ArgumentError.notNull('origin');
}
if (destination == null) {
throw ArgumentError.notNull('destination');
}
return true;
}());
var value = _polylines.remove('${origin}_$destination');
final start = value?.points?.firstOrNull?.toGeoCoord();
if (start != null) {
removeMarker(start);
_directionMarkerCoords.remove(start);
}
final end = value?.points?.lastOrNull?.toGeoCoord();
if (end != null) {
removeMarker(end);
_directionMarkerCoords.remove(end);
}
value = null;
}
@override
void clearDirections() {
for (var polyline in _polylines.values) {
final start = polyline?.points?.firstOrNull?.toGeoCoord();
if (start != null) {
removeMarker(start);
_directionMarkerCoords.remove(start);
}
final end = polyline?.points?.lastOrNull?.toGeoCoord();
if (end != null) {
removeMarker(end);
_directionMarkerCoords.remove(end);
}
polyline = null;
}
_polylines.clear();
}
@override
void addPolygon(
String id,
Iterable<GeoCoord> points, {
ValueChanged<String> onTap,
Color strokeColor = const Color(0x000000),
double strokeOpacity = 0.8,
double strokeWidth = 1,
Color fillColor = const Color(0x000000),
double fillOpacity = 0.35,
}) {
assert(() {
if (id == null) {
throw ArgumentError.notNull('id');
}
if (points == null) {
throw ArgumentError.notNull('position');
}
if (points.isEmpty) {
throw ArgumentError.value(<GeoCoord>[], 'points');
}
if (points.length < 3) {
throw ArgumentError('Polygon must have at least 3 coordinates');
}
return true;
}());
_polygons.putIfAbsent(
id,
() => Polygon(
polygonId: PolygonId(id),
points: points.mapList((_) => _.toLatLng()),
consumeTapEvents: onTap != null,
onTap: onTap != null ? () => onTap(id) : null,
strokeWidth: strokeWidth?.toInt() ?? 1,
strokeColor: (strokeColor ?? const Color(0x000000))
.withOpacity(strokeOpacity ?? 0.8),
fillColor: (fillColor ?? const Color(0x000000))
.withOpacity(fillOpacity ?? 0.35),
),
);
}
@override
void editPolygon(
String id,
Iterable<GeoCoord> points, {
ValueChanged<String> onTap,
Color strokeColor = const Color(0x000000),
double strokeOpacity = 0.8,
double strokeWeight = 1,
Color fillColor = const Color(0x000000),
double fillOpacity = 0.35,
}) {
removePolygon(id);
addPolygon(
id,
points,
onTap: onTap,
strokeColor: strokeColor,
strokeOpacity: strokeOpacity,
strokeWidth: strokeWeight,
fillColor: fillColor,
fillOpacity: fillOpacity,
);
}
@override
void removePolygon(String id) {
assert(() {
if (id == null) {
throw ArgumentError.notNull('id');
}
return true;
}());
if (!_polygons.containsKey(id)) return;
_setState(() => _polygons.remove(id));
}
@override
void clearPolygons() => _setState(() => _polygons.clear());
@override
void initState() {
super.initState();
if (widget.markers != null) {
for (var marker in widget.markers) {
addMarker(marker);
}
}
}
@override
Widget build(BuildContext context) => LayoutBuilder(
builder: (context, constraints) => IgnorePointer(
ignoring: !widget.interactive,
child: Container(
constraints: BoxConstraints(maxHeight: constraints.maxHeight),
child: GoogleMap(
markers: Set<Marker>.of(_markers.values),
polygons: Set<Polygon>.of(_polygons.values),
polylines: Set<Polyline>.of(_polylines.values),
mapType: MapType.values[widget.mapType.index],
minMaxZoomPreference:
MinMaxZoomPreference(widget.minZoom, widget.minZoom),
initialCameraPosition: CameraPosition(
target: widget.initialPosition.toLatLng(),
zoom: widget.initialZoom,
),
onTap: (coords) => widget.onTap?.call(coords?.toGeoCoord()),
onLongPress: (coords) =>
widget.onLongPress?.call(coords?.toGeoCoord()),
onCameraMove: (position) =>
widget.onMapMove?.call(position),
onMapCreated: (GoogleMapController controller) {
_controller = controller;
_controller.setMapStyle(widget.mapStyle);
_waitUntilReadyCompleter.complete();
},
padding: widget.mobilePreferences.padding,
compassEnabled: widget.mobilePreferences.compassEnabled,
trafficEnabled: widget.mobilePreferences.trafficEnabled,
buildingsEnabled: widget.mobilePreferences.buildingsEnabled,
indoorViewEnabled: widget.mobilePreferences.indoorViewEnabled,
mapToolbarEnabled: widget.mobilePreferences.mapToolbarEnabled,
myLocationEnabled: widget.mobilePreferences.myLocationEnabled,
myLocationButtonEnabled:
widget.mobilePreferences.myLocationButtonEnabled,
tiltGesturesEnabled: widget.mobilePreferences.tiltGesturesEnabled,
zoomGesturesEnabled: widget.mobilePreferences.zoomGesturesEnabled,
rotateGesturesEnabled:
widget.mobilePreferences.rotateGesturesEnabled,
zoomControlsEnabled: widget.mobilePreferences.zoomControlsEnabled,
scrollGesturesEnabled:
widget.mobilePreferences.scrollGesturesEnabled,
),
),
),
);
@override
void dispose() {
super.dispose();
_markers.clear();
_polygons.clear();
_polylines.clear();
_directionMarkerCoords.clear();
_controller = null;
}
}