-
Notifications
You must be signed in to change notification settings - Fork 494
/
mapbox_map_controller.dart
690 lines (608 loc) · 18.9 KB
/
mapbox_map_controller.dart
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
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
part of mapbox_gl_web;
const _mapboxGlCssUrl =
'https://api.tiles.mapbox.com/mapbox-gl-js/v1.6.1/mapbox-gl.css';
class MapboxMapController extends MapboxGlPlatform
implements MapboxMapOptionsSink {
DivElement _mapElement;
Map<String, dynamic> _creationParams;
MapboxMap _map;
SymbolManager symbolManager;
LineManager lineManager;
CircleManager circleManager;
FillManager fillManager;
bool _trackCameraPosition = false;
GeolocateControl _geolocateControl;
LatLng _myLastLocation;
String _navigationControlPosition;
NavigationControl _navigationControl;
@override
Widget buildView(
Map<String, dynamic> creationParams,
Function onPlatformViewCreated,
Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers) {
_creationParams = creationParams;
_registerViewFactory(onPlatformViewCreated, this.hashCode);
return HtmlElementView(
viewType: 'plugins.flutter.io/mapbox_gl_${this.hashCode}');
}
void _registerViewFactory(Function(int) callback, int identifier) {
// ignore: undefined_prefixed_name
ui.platformViewRegistry.registerViewFactory(
'plugins.flutter.io/mapbox_gl_$identifier', (int viewId) {
_mapElement = DivElement();
callback(viewId);
return _mapElement;
});
}
@override
Future<void> initPlatform(int id) async {
await _addStylesheetToShadowRoot(_mapElement);
if (_creationParams.containsKey('initialCameraPosition')) {
var camera = _creationParams['initialCameraPosition'];
if (_creationParams.containsKey('accessToken')) {
Mapbox.accessToken = _creationParams['accessToken'];
}
_map = MapboxMap(
MapOptions(
container: _mapElement,
style: 'mapbox://styles/mapbox/streets-v11',
center: LngLat(camera['target'][1], camera['target'][0]),
zoom: camera['zoom'],
bearing: camera['bearing'],
pitch: camera['tilt'],
),
);
_map.on('load', _onStyleLoaded);
}
Convert.interpretMapboxMapOptions(_creationParams['options'], this);
}
Future<void> _addStylesheetToShadowRoot(HtmlElement e) async {
LinkElement link = LinkElement()
..href = _mapboxGlCssUrl
..rel = 'stylesheet';
e.append(link);
await link.onLoad.first;
}
@override
Future<CameraPosition> updateMapOptions(
Map<String, dynamic> optionsUpdate) async {
// FIX: why is called indefinitely? (map_ui page)
Convert.interpretMapboxMapOptions(optionsUpdate, this);
return _getCameraPosition();
}
@override
Future<bool> animateCamera(CameraUpdate cameraUpdate) async {
final cameraOptions = Convert.toCameraOptions(cameraUpdate, _map);
if (cameraOptions != null) {
_map.flyTo(cameraOptions);
}
return true;
}
@override
Future<bool> moveCamera(CameraUpdate cameraUpdate) async {
final cameraOptions = Convert.toCameraOptions(cameraUpdate, _map);
if (cameraOptions != null) {
_map.jumpTo(cameraOptions);
}
return true;
}
@override
Future<void> updateMyLocationTrackingMode(
MyLocationTrackingMode myLocationTrackingMode) async {
setMyLocationTrackingMode(myLocationTrackingMode.index);
}
@override
Future<void> matchMapLanguageWithDeviceDefault() async {
setMapLanguage(ui.window.locale.languageCode);
}
@override
Future<void> setMapLanguage(String language) async {
_map.setLayoutProperty(
'country-label',
'text-field',
['get', 'name_' + language],
);
}
@override
Future<void> setTelemetryEnabled(bool enabled) async {
print('Telemetry not available in web');
return;
}
@override
Future<bool> getTelemetryEnabled() async {
print('Telemetry not available in web');
return false;
}
@override
Future<List<Symbol>> addSymbols(List<SymbolOptions> options,
[List<Map> data]) async {
Map<String, SymbolOptions> optionsById = Map.fromIterable(options,
key: (o) => symbolManager.add(Feature(
geometry: Geometry(
type: 'Point',
coordinates: [o.geometry.longitude, o.geometry.latitude],
),
)),
value: (o) => o);
symbolManager.updateAll(optionsById);
return optionsById
.map((id, singleOptions) {
int dataIndex = options.indexOf(singleOptions);
Map singleData = data != null && data.length >= dataIndex + 1
? data[dataIndex]
: null;
return MapEntry(id, Symbol(id, singleOptions, singleData));
})
.values
.toList();
}
@override
Future<void> updateSymbol(Symbol symbol, SymbolOptions changes) async {
symbolManager.update(symbol.id, changes);
}
@override
Future<void> removeSymbols(Iterable<String> symbolsIds) async {
symbolManager.removeAll(symbolsIds);
}
@override
Future<Line> addLine(LineOptions options, [Map data]) async {
String lineId = lineManager.add(Feature(
geometry: Geometry(
type: 'LineString',
coordinates: options.geometry
.map((latLng) => [latLng.longitude, latLng.latitude])
.toList(),
),
));
lineManager.update(lineId, options);
return Line(lineId, options, data);
}
@override
Future<void> updateLine(Line line, LineOptions changes) async {
lineManager.update(line.id, changes);
}
@override
Future<void> removeLine(String lineId) async {
lineManager.remove(lineId);
}
@override
Future<Circle> addCircle(CircleOptions options, [Map data]) async {
String circleId = circleManager.add(Feature(
geometry: Geometry(
type: 'Point',
coordinates: [options.geometry.longitude, options.geometry.latitude],
),
));
circleManager.update(circleId, options);
return Circle(circleId, options, data);
}
@override
Future<void> updateCircle(Circle circle, CircleOptions changes) async {
circleManager.update(circle.id, changes);
}
@override
Future<LatLng> getCircleLatLng(Circle circle) async {
var coordinates = circleManager.getFeature(circle.id).geometry.coordinates;
return LatLng(coordinates[1], coordinates[0]);
}
@override
Future<void> removeCircle(String circleId) async {
circleManager.remove(circleId);
}
Future<Fill> addFill(FillOptions options, [Map data]) async {
String fillId = fillManager.add(Feature(
geometry: Geometry(
type: 'Polygon',
coordinates: Convert.fillGeometryToFeatureGeometry(options.geometry),
),
));
fillManager.update(fillId, options);
return Fill(fillId, options, data);
}
Future<void> updateFill(Fill fill, FillOptions changes) async {
fillManager.update(fill.id, changes);
}
Future<void> removeFill(String fillId) async {
fillManager.remove(fillId);
}
@override
Future<List> queryRenderedFeatures(
Point<double> point, List<String> layerIds, List<Object> filter) async {
Map<String, dynamic> options = {};
if (layerIds.length > 0) {
options['layers'] = layerIds;
}
if (filter != null) {
options['filter'] = filter;
}
return _map.queryRenderedFeatures([point, point], options);
}
@override
Future<List> queryRenderedFeaturesInRect(
Rect rect, List<String> layerIds, String filter) async {
Map<String, dynamic> options = {};
if (layerIds.length > 0) {
options['layers'] = layerIds;
}
if (filter != null) {
options['filter'] = filter;
}
return _map.queryRenderedFeatures([
Point(rect.left, rect.bottom),
Point(rect.right, rect.top),
], options);
}
@override
Future invalidateAmbientCache() async {
print('Offline storage not available in web');
}
@override
Future<LatLng> requestMyLocationLatLng() async {
return _myLastLocation;
}
@override
Future<LatLngBounds> getVisibleRegion() async {
final bounds = _map.getBounds();
return LatLngBounds(
southwest: LatLng(bounds.getSouthWest().lat, bounds.getSouthWest().lng),
northeast: LatLng(bounds.getNorthEast().lat, bounds.getNorthEast().lng),
);
}
@override
Future<void> addImage(String name, Uint8List bytes,
[bool sdf = false]) async {
final photo = decodeImage(bytes);
if (!_map.hasImage(name)) {
_map.addImage(
name,
{
'width': photo.width,
'height': photo.height,
'data': photo.getBytes(),
},
{'sdf': sdf},
);
}
}
@override
Future<void> setSymbolIconAllowOverlap(bool enable) async {
//TODO: to implement
print('setSymbolIconAllowOverlap not implemented yet');
}
@override
Future<void> setSymbolIconIgnorePlacement(bool enable) async {
//TODO: to implement
print('setSymbolIconIgnorePlacement not implemented yet');
}
@override
Future<void> setSymbolTextAllowOverlap(bool enable) async {
//TODO: to implement
print('setSymbolTextAllowOverlap not implemented yet');
}
@override
Future<void> setSymbolTextIgnorePlacement(bool enable) async {
//TODO: to implement
print('setSymbolTextIgnorePlacement not implemented yet');
}
CameraPosition _getCameraPosition() {
if (_trackCameraPosition) {
final center = _map.getCenter();
return CameraPosition(
bearing: _map.getBearing(),
target: LatLng(center.lat, center.lng),
tilt: _map.getPitch(),
zoom: _map.getZoom(),
);
}
return null;
}
void _onStyleLoaded(_) {
symbolManager = SymbolManager(map: _map, onTap: onSymbolTappedPlatform);
lineManager = LineManager(map: _map, onTap: onLineTappedPlatform);
circleManager = CircleManager(map: _map, onTap: onCircleTappedPlatform);
fillManager = FillManager(map: _map, onTap: onFillTappedPlatform);
onMapStyleLoadedPlatform(null);
_map.on('click', _onMapClick);
// long click not available in web, so it is mapped to double click
_map.on('dblclick', _onMapLongClick);
_map.on('movestart', _onCameraMoveStarted);
_map.on('move', _onCameraMove);
_map.on('moveend', _onCameraIdle);
_map.on('resize', _onMapResize);
}
void _onMapResize(Event e) {
Timer(Duration(microseconds: 10), () {
var container = _map.getContainer();
var canvas = _map.getCanvas();
var widthMismatch = canvas.clientWidth != container.clientWidth;
var heightMismatch = canvas.clientHeight != container.clientHeight;
if (widthMismatch || heightMismatch) {
_map.resize();
}
});
}
void _onMapClick(e) {
onMapClickPlatform({
'point': Point<double>(e.point.x, e.point.y),
'latLng': LatLng(e.lngLat.lat, e.lngLat.lng),
});
}
void _onMapLongClick(e) {
onMapLongClickPlatform({
'point': Point<double>(e.point.x, e.point.y),
'latLng': LatLng(e.lngLat.lat, e.lngLat.lng),
});
}
void _onCameraMoveStarted(_) {
onCameraMoveStartedPlatform(null);
}
void _onCameraMove(_) {
final center = _map.getCenter();
var camera = CameraPosition(
bearing: _map.getBearing(),
target: LatLng(center.lat, center.lng),
tilt: _map.getPitch(),
zoom: _map.getZoom(),
);
onCameraMovePlatform(camera);
}
void _onCameraIdle(_) {
final center = _map.getCenter();
var camera = CameraPosition(
bearing: _map.getBearing(),
target: LatLng(center.lat, center.lng),
tilt: _map.getPitch(),
zoom: _map.getZoom(),
);
onCameraIdlePlatform(camera);
}
void _onCameraTrackingChanged(bool isTracking) {
if (isTracking) {
onCameraTrackingChangedPlatform(MyLocationTrackingMode.Tracking);
} else {
onCameraTrackingChangedPlatform(MyLocationTrackingMode.None);
}
}
void _onCameraTrackingDismissed() {
onCameraTrackingDismissedPlatform(null);
}
void _addGeolocateControl({bool trackUserLocation}) {
_removeGeolocateControl();
_geolocateControl = GeolocateControl(
GeolocateControlOptions(
positionOptions: PositionOptions(enableHighAccuracy: true),
trackUserLocation: trackUserLocation ?? false,
showAccuracyCircle: true,
showUserLocation: true,
),
);
_geolocateControl.on('geolocate', (e) {
_myLastLocation = LatLng(e.coords.latitude, e.coords.longitude);
onUserLocationUpdatedPlatform(UserLocation(
position: LatLng(e.coords.latitude, e.coords.longitude),
altitude: e.coords.altitude,
bearing: e.coords.heading,
speed: e.coords.speed,
horizontalAccuracy: e.coords.accuracy,
verticalAccuracy: e.coords.altitudeAccuracy,
heading: null,
timestamp: DateTime.fromMillisecondsSinceEpoch(e.timestamp)));
});
_geolocateControl.on('trackuserlocationstart', (_) {
_onCameraTrackingChanged(true);
});
_geolocateControl.on('trackuserlocationend', (_) {
_onCameraTrackingChanged(false);
_onCameraTrackingDismissed();
});
_map.addControl(_geolocateControl, 'bottom-right');
}
void _removeGeolocateControl() {
if (_geolocateControl != null) {
_map.removeControl(_geolocateControl);
_geolocateControl = null;
}
}
void _updateNavigationControl({
bool compassEnabled,
CompassViewPosition position,
}) {
bool prevShowCompass;
if (_navigationControl != null) {
prevShowCompass = _navigationControl.options.showCompass;
}
String prevPosition = _navigationControlPosition;
String positionString;
switch (position) {
case CompassViewPosition.TopRight:
positionString = 'top-right';
break;
case CompassViewPosition.TopLeft:
positionString = 'top-left';
break;
case CompassViewPosition.BottomRight:
positionString = 'bottom-right';
break;
case CompassViewPosition.BottomLeft:
positionString = 'bottom-left';
break;
default:
positionString = null;
}
bool newShowComapss = compassEnabled ?? prevShowCompass ?? false;
String newPosition = positionString ?? prevPosition ?? null;
_removeNavigationControl();
_navigationControl = NavigationControl(NavigationControlOptions(
showCompass: newShowComapss,
showZoom: false,
visualizePitch: false,
));
if (newPosition == null) {
_map.addControl(_navigationControl);
} else {
_map.addControl(_navigationControl, newPosition);
_navigationControlPosition = newPosition;
}
}
void _removeNavigationControl() {
if (_navigationControl != null) {
_map.removeControl(_navigationControl);
_navigationControl = null;
}
}
/*
* MapboxMapOptionsSink
*/
@override
void setAttributionButtonMargins(int x, int y) {
print('setAttributionButtonMargins not available in web');
}
@override
void setCameraTargetBounds(LatLngBounds bounds) {
if (bounds == null) {
_map.setMaxBounds(null);
} else {
_map.setMaxBounds(
LngLatBounds(
LngLat(
bounds.southwest.longitude,
bounds.southwest.latitude,
),
LngLat(
bounds.northeast.longitude,
bounds.northeast.latitude,
),
),
);
}
}
@override
void setCompassEnabled(bool compassEnabled) {
_updateNavigationControl(compassEnabled: compassEnabled);
}
@override
void setCompassGravity(int gravity) {
_updateNavigationControl(position: CompassViewPosition.values[gravity]);
}
@override
void setCompassViewMargins(int x, int y) {
print('setCompassViewMargins not available in web');
}
@override
void setLogoViewMargins(int x, int y) {
print('setLogoViewMargins not available in web');
}
@override
void setMinMaxZoomPreference(num min, num max) {
// FIX: why is called indefinitely? (map_ui page)
_map.setMinZoom(min);
_map.setMaxZoom(max);
}
@override
void setMyLocationEnabled(bool myLocationEnabled) {
if (myLocationEnabled) {
_addGeolocateControl(trackUserLocation: false);
} else {
_removeGeolocateControl();
}
}
@override
void setMyLocationRenderMode(int myLocationRenderMode) {
print('myLocationRenderMode not available in web');
}
@override
void setMyLocationTrackingMode(int myLocationTrackingMode) {
if (_geolocateControl == null) {
//myLocationEnabled is false, ignore myLocationTrackingMode
return;
}
if (myLocationTrackingMode == 0) {
_addGeolocateControl(trackUserLocation: false);
} else {
print('Only one tracking mode available in web');
_addGeolocateControl(trackUserLocation: true);
}
}
@override
void setRotateGesturesEnabled(bool rotateGesturesEnabled) {
if (rotateGesturesEnabled) {
_map.dragRotate.enable();
_map.touchZoomRotate.enableRotation();
_map.keyboard.enable();
} else {
_map.dragRotate.disable();
_map.touchZoomRotate.disableRotation();
_map.keyboard.disable();
}
}
@override
void setScrollGesturesEnabled(bool scrollGesturesEnabled) {
if (scrollGesturesEnabled) {
_map.dragPan.enable();
_map.keyboard.enable();
} else {
_map.dragPan.disable();
_map.keyboard.disable();
}
}
@override
void setStyleString(String styleString) {
_map.setStyle(styleString);
}
@override
void setTiltGesturesEnabled(bool tiltGesturesEnabled) {
if (tiltGesturesEnabled) {
_map.dragRotate.enable();
_map.keyboard.enable();
} else {
_map.dragRotate.disable();
_map.keyboard.disable();
}
}
@override
void setTrackCameraPosition(bool trackCameraPosition) {
_trackCameraPosition = trackCameraPosition;
}
@override
void setZoomGesturesEnabled(bool zoomGesturesEnabled) {
if (zoomGesturesEnabled) {
_map.doubleClickZoom.enable();
_map.boxZoom.enable();
_map.scrollZoom.enable();
_map.touchZoomRotate.enable();
_map.keyboard.enable();
} else {
_map.doubleClickZoom.disable();
_map.boxZoom.disable();
_map.scrollZoom.disable();
_map.touchZoomRotate.disable();
_map.keyboard.disable();
}
}
@override
Future<Point> toScreenLocation(LatLng latLng) async {
var screenPosition =
_map.project(LngLat(latLng.longitude, latLng.latitude));
return Point(screenPosition.x.round(), screenPosition.y.round());
}
@override
Future<List<Point>> toScreenLocationBatch(Iterable<LatLng> latLngs) async {
return latLngs.map((latLng) {
var screenPosition = _map.project(LngLat(latLng.longitude, latLng.latitude));
return Point(screenPosition.x.round(), screenPosition.y.round());
}).toList(growable: false);
}
@override
Future<LatLng> toLatLng(Point screenLocation) async {
var lngLat =
_map.unproject(mapbox.Point(screenLocation.x, screenLocation.y));
return LatLng(lngLat.lat, lngLat.lng);
}
@override
Future<double> getMetersPerPixelAtLatitude(double latitude) async {
//https://wiki.openstreetmap.org/wiki/Zoom_levels
var circumference = 40075017.686;
var zoom = _map.getZoom();
return circumference * cos(latitude * (pi / 180)) / pow(2, zoom + 9);
}
}