@nativescript-community/ui-mapbox 6.2.31 → 7.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/common.d.ts +56 -26
  3. package/common.js +44 -28
  4. package/expression/expression-parser.android.d.ts +2 -2
  5. package/expression/expression-parser.android.js +4 -3
  6. package/expression/expression-parser.ios.d.ts +2 -2
  7. package/expression/expression-parser.ios.js +28 -13
  8. package/index.android.d.ts +59 -66
  9. package/index.android.js +1388 -1244
  10. package/index.d.ts +36 -5
  11. package/index.ios.d.ts +72 -243
  12. package/index.ios.js +1161 -1999
  13. package/layers/layer-factory.android.d.ts +7 -5
  14. package/layers/layer-factory.android.js +71 -41
  15. package/layers/layer-factory.d.ts +2 -1
  16. package/layers/layer-factory.ios.d.ts +8 -8
  17. package/layers/layer-factory.ios.js +46 -100
  18. package/layers/parser/property-parser.android.d.ts +3 -1
  19. package/layers/parser/property-parser.android.js +25 -24
  20. package/layers/parser/property-parser.d.ts +1 -1
  21. package/layers/parser/property-parser.ios.d.ts +0 -2
  22. package/layers/parser/property-parser.ios.js +0 -149
  23. package/markers/Marker.android.d.ts +28 -0
  24. package/markers/Marker.android.js +54 -0
  25. package/markers/Marker.common.d.ts +2 -0
  26. package/markers/Marker.common.js +31 -0
  27. package/markers/MarkerManager.android.d.ts +35 -0
  28. package/markers/MarkerManager.android.js +220 -0
  29. package/package.json +7 -6
  30. package/platforms/android/include.gradle +31 -27
  31. package/platforms/android/ui_mapbox.aar +0 -0
  32. package/platforms/ios/Podfile +3 -1
  33. package/platforms/ios/Resources/default_pin.png +0 -0
  34. package/platforms/ios/src/MapboxBridge.swift +1479 -0
  35. package/platforms/ios/src/NativeExpressionParser.swift +33 -0
  36. package/platforms/ios/src/NativeLayerFactory.swift +108 -0
  37. package/tsconfig.tsbuildinfo +1 -0
  38. package/typings/Mapbox.ios.d.ts +2 -3242
  39. package/typings/geojson.android.d.ts +689 -0
  40. package/typings/index.android.d.ts +46 -0
  41. package/typings/mapbox.android.d.ts +39968 -12560
  42. package/typings/mapbox.bridge.ios.d.ts +129 -0
package/index.android.js CHANGED
@@ -3,36 +3,50 @@
3
3
  *
4
4
  * @todo FIXME: The gcFix() implementation currently assumes only one map visible at a time.
5
5
  */
6
- import { request } from '@nativescript-community/perms';
7
- import { AndroidApplication, Application, Color, File, Http, ImageSource, Trace, Utils, knownFolders, path } from '@nativescript/core';
6
+ import { Application, Color, File, Http, ImageSource, Trace, Utils, knownFolders, path } from '@nativescript/core';
8
7
  import { ExpressionParser } from './expression/expression-parser';
9
8
  import { Layer, LayerFactory } from './layers/layer-factory';
10
9
  import { CLog, CLogTypes, ControlPosition, MapStyle, MapboxCommon, MapboxViewBase, telemetryProperty } from './common';
10
+ import { MarkerManager } from './markers/MarkerManager.android';
11
+ import { AndroidMarker } from './markers/Marker.android';
11
12
  // Export the enums for devs not using TS
12
13
  export * from './common';
13
- let libraryLoadedOverloaded = false;
14
- function overrideLibraryLoader() {
15
- try {
16
- if (true && !libraryLoadedOverloaded) {
17
- var LibraryLoader = /** @class */ (function (_super) {
18
- __extends(LibraryLoader, _super);
19
- function LibraryLoader() {
20
- return _super !== null && _super.apply(this, arguments) || this;
21
- }
22
- LibraryLoader.prototype.load = function (name) {
23
- java.lang.System.loadLibrary(name);
24
- };
25
- return LibraryLoader;
26
- }(com.mapbox.mapboxsdk.LibraryLoader));
27
- com.mapbox.mapboxsdk.LibraryLoader.setLibraryLoader(new LibraryLoader());
28
- libraryLoadedOverloaded = true;
29
- }
30
- }
31
- catch (error) {
32
- console.error(error);
14
+ function bitmapFromDrawableResource(resourceId) {
15
+ // 1. Get the Drawable
16
+ const context = Utils.android.getApplicationContext();
17
+ const identifier = context.getResources().getIdentifier(resourceId, 'drawable', Utils.android.getApplication().getPackageName());
18
+ // if (identifier !== 0) {
19
+ if (0 < identifier) {
20
+ const drawable = androidx.core.content.ContextCompat.getDrawable(context, identifier);
21
+ // 2. Create a Bitmap with the same dimensions
22
+ const width = drawable.getIntrinsicWidth();
23
+ const height = drawable.getIntrinsicHeight();
24
+ const bitmap = android.graphics.Bitmap.createBitmap(width, height, android.graphics.Bitmap.Config.ARGB_8888);
25
+ // 3. Create a Canvas to draw onto the Bitmap
26
+ const canvas = new android.graphics.Canvas(bitmap);
27
+ drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
28
+ drawable.draw(canvas);
29
+ return bitmap;
33
30
  }
34
31
  }
35
- overrideLibraryLoader();
32
+ // let libraryLoadedOverloaded = false;
33
+ // function overrideLibraryLoader() {
34
+ // try {
35
+ // if (true && !libraryLoadedOverloaded) {
36
+ // @NativeClass
37
+ // class LibraryLoader extends com.mapbox.maps.LibraryLoader {
38
+ // load(name) {
39
+ // java.lang.System.loadLibrary(name);
40
+ // }
41
+ // }
42
+ // com.mapbox.maps.LibraryLoader.setLibraryLoader(new LibraryLoader());
43
+ // libraryLoadedOverloaded = true;
44
+ // }
45
+ // } catch (error) {
46
+ // console.error(error);
47
+ // }
48
+ // }
49
+ // overrideLibraryLoader();
36
50
  function _getLocation(loc) {
37
51
  if (loc === null) {
38
52
  return null;
@@ -48,27 +62,28 @@ function _getLocation(loc) {
48
62
  }
49
63
  }
50
64
  export function setLogLevel(level) {
51
- const Logger = com.mapbox.mapboxsdk.log.Logger;
52
- let loggingLevel;
53
- switch (level) {
54
- case 'none':
55
- loggingLevel = Logger.NONE;
56
- break;
57
- case 'info':
58
- loggingLevel = Logger.INFO;
59
- break;
60
- case 'debug':
61
- loggingLevel = Logger.DEBUG;
62
- break;
63
- case 'verbose':
64
- loggingLevel = Logger.VERBOSE;
65
- break;
66
- case 'fault':
67
- case 'error':
68
- loggingLevel = Logger.ERROR;
69
- break;
70
- }
71
- Logger.setVerbosity(loggingLevel);
65
+ //TODO: Logger
66
+ // const Logger = com.mapbox.maps.log.Logger;
67
+ // let loggingLevel: number;
68
+ // switch (level) {
69
+ // case 'none':
70
+ // loggingLevel = Logger.NONE;
71
+ // break;
72
+ // case 'info':
73
+ // loggingLevel = Logger.INFO;
74
+ // break;
75
+ // case 'debug':
76
+ // loggingLevel = Logger.DEBUG;
77
+ // break;
78
+ // case 'verbose':
79
+ // loggingLevel = Logger.VERBOSE;
80
+ // break;
81
+ // case 'fault':
82
+ // case 'error':
83
+ // loggingLevel = Logger.ERROR;
84
+ // break;
85
+ // }
86
+ // Logger.setVerbosity(loggingLevel);
72
87
  }
73
88
  /**
74
89
  * A map view created in XML.
@@ -169,8 +184,8 @@ export class MapboxView extends MapboxViewBase {
169
184
  }
170
185
  this.nativeView.owner = this;
171
186
  // Application.android.on(AndroidApplication.activityStartedEvent, this.onStart, this);
172
- Application.android.on(AndroidApplication.activityPausedEvent, this.onPause, this);
173
- Application.android.on(AndroidApplication.activityResumedEvent, this.onResume, this);
187
+ // Application.android.on(Application.android.activityPausedEvent, this.onPause, this);
188
+ // Application.android.on(Application.android.activityResumedEvent, this.onResume, this);
174
189
  // Application.android.on(AndroidApplication.activityStartedEvent, this.onStop, this);
175
190
  super.initNativeView();
176
191
  }
@@ -188,13 +203,8 @@ export class MapboxView extends MapboxViewBase {
188
203
  CLog(CLogTypes.info, 'disposeNativeView(): top');
189
204
  }
190
205
  this.nativeView.owner = null;
191
- // Application.android.off(AndroidApplication.activityStartedEvent, this.onStart, this);
192
- Application.android.off(AndroidApplication.activityPausedEvent, this.onPause, this);
193
- Application.android.off(AndroidApplication.activityResumedEvent, this.onResume, this);
194
- // Application.android.off(AndroidApplication.activityStartedEvent, this.onStop, this);
195
- if (this.mapbox) {
196
- this.mapbox.destroy();
197
- }
206
+ this.mapbox?.destroy();
207
+ this.mapbox = null;
198
208
  super.disposeNativeView();
199
209
  }
200
210
  /**
@@ -209,10 +219,13 @@ export class MapboxView extends MapboxViewBase {
209
219
  *
210
220
  * @todo FIXME: this.nativeMapView is unused and never actually set to anything.
211
221
  */
212
- initMap() {
222
+ async initMap() {
213
223
  if (Trace.isEnabled()) {
214
224
  CLog(CLogTypes.info, "MapboxView:initMap(): top - accessToken is '" + this.config.accessToken + "'", this.config);
215
225
  }
226
+ if (!this.config.accessToken) {
227
+ throw new Error('missing accessToken');
228
+ }
216
229
  if (!this.nativeMapView && ((this.config && this.config.accessToken) || (this.settings && this.settings.accessToken))) {
217
230
  this.mapbox = new Mapbox(this);
218
231
  // the NativeScript contentview class extends from Observable to provide the notify method
@@ -237,14 +250,10 @@ export class MapboxView extends MapboxViewBase {
237
250
  android: this.nativeMapView
238
251
  });
239
252
  },
240
- onMapReady: (map) => {
253
+ onMapReady: (map, view) => {
254
+ this.nativeMapView = view;
241
255
  if (this.telemetry === false) {
242
- try {
243
- com.mapbox.mapboxsdk.Mapbox.getTelemetry().setUserTelemetryRequestState(false);
244
- }
245
- catch (err) {
246
- console.error('telemtry', err);
247
- }
256
+ com.nativescript.mapbox.Telemetry.setUserTelemetryRequestState(this.nativeMapView, false);
248
257
  }
249
258
  if (Trace.isEnabled()) {
250
259
  CLog(CLogTypes.info, 'initMap(): onMapReady event - calling notify with the MapboxViewBase.mapReadyEvent');
@@ -268,7 +277,7 @@ export class MapboxView extends MapboxViewBase {
268
277
  },
269
278
  onScrollEvent: (event) => {
270
279
  if (Trace.isEnabled()) {
271
- CLog(CLogTypes.info, 'initMap(): onScrollEvent event');
280
+ CLog(CLogTypes.info, 'initMap(): onScrollEvent event:' + JSON.stringify(event));
272
281
  }
273
282
  this.notify({
274
283
  eventName: MapboxViewBase.scrollEvent,
@@ -316,16 +325,14 @@ export class MapboxView extends MapboxViewBase {
316
325
  if (Trace.isEnabled()) {
317
326
  CLog(CLogTypes.info, 'initMap(): before show.');
318
327
  }
319
- this.mapbox.show(this.settings);
328
+ await this.mapbox.show(this.settings);
320
329
  if (Trace.isEnabled()) {
321
330
  CLog(CLogTypes.info, 'initMap(): bottom.');
322
331
  }
323
332
  }
324
333
  }
325
334
  [telemetryProperty.setNative](value) {
326
- if (com.mapbox.mapboxsdk.Mapbox.getTelemetry()) {
327
- com.mapbox.mapboxsdk.Mapbox.getTelemetry().setUserTelemetryRequestState(value);
328
- }
335
+ com.nativescript.mapbox.Telemetry.setUserTelemetryRequestState(this.nativeMapView, false);
329
336
  }
330
337
  }
331
338
  /**
@@ -341,19 +348,23 @@ export class MapboxView extends MapboxViewBase {
341
348
  export class Mapbox extends MapboxCommon {
342
349
  constructor(view) {
343
350
  super(view);
351
+ // private _locationComponent: com.mapbox.maps.plugin.locationcomponent.LocationComponent;
344
352
  this._accessToken = '';
345
- this.circleManager = null;
353
+ // private circleManager: any = null;
346
354
  this.lineManager = null;
347
- this.symbolManager = null;
355
+ this.polygonManager = null;
356
+ this.customMarker = null;
357
+ // private iconFactory;
348
358
  this._markers = [];
349
- this._polylines = [];
350
- this._polygons = [];
359
+ this._polylines = {};
360
+ this._polygons = {};
351
361
  // list of polylines
352
362
  this.lines = [];
353
363
  // registered callbacks.
354
364
  this.eventCallbacks = {};
355
- this._markerIconDownloadCache = [];
365
+ this._markerIconDownloadCache = {};
356
366
  this.iconCache = {};
367
+ this._plugins = {};
357
368
  if (Trace.isEnabled()) {
358
369
  CLog(CLogTypes.info, 'constructor(): building new Mapbox object.');
359
370
  }
@@ -385,148 +396,178 @@ export class Mapbox extends MapboxCommon {
385
396
  *
386
397
  * @todo FIXME: the timeout delay before showing the map works around some race condition. The source error needs to be figured out.
387
398
  */
388
- show(options) {
399
+ async show(options) {
389
400
  return new Promise((resolve, reject) => {
390
401
  try {
391
402
  const settings = Mapbox.merge(options, Mapbox.defaults);
392
- const showIt = () => {
403
+ // const showIt = () => {
404
+ if (Trace.isEnabled()) {
405
+ CLog(CLogTypes.info, 'show(): ' + JSON.stringify(settings.center));
406
+ }
407
+ // if no accessToken was set the app may crash.
408
+ //
409
+ // FIXME: Even if using a local server add some string.
410
+ if (settings.accessToken === undefined) {
411
+ throw new Error('mapbox_accesstoken_missing');
412
+ }
413
+ // if already added, make sure it's removed first
414
+ if (this._mapboxViewInstance) {
393
415
  if (Trace.isEnabled()) {
394
- CLog(CLogTypes.info, 'show()');
395
- }
396
- // if no accessToken was set the app may crash.
397
- //
398
- // FIXME: Even if using a local server add some string.
399
- if (settings.accessToken === undefined) {
400
- reject('mapbox_accesstoken_missing');
401
- return;
416
+ CLog(CLogTypes.info, 'show(): view already created. Removing it.');
402
417
  }
403
- // if already added, make sure it's removed first
404
- if (this._mapboxViewInstance) {
418
+ const viewGroup = this._mapboxViewInstance.getParent();
419
+ if (viewGroup !== null) {
405
420
  if (Trace.isEnabled()) {
406
- CLog(CLogTypes.info, 'show(): view already created. Removing it.');
407
- }
408
- const viewGroup = this._mapboxViewInstance.getParent();
409
- if (viewGroup !== null) {
410
- if (Trace.isEnabled()) {
411
- CLog(CLogTypes.info, 'show(): view already created. Removing _mapboxViewInstance child of view parent.');
412
- }
413
- viewGroup.removeView(this._mapboxViewInstance);
421
+ CLog(CLogTypes.info, 'show(): view already created. Removing _mapboxViewInstance child of view parent.');
414
422
  }
423
+ viewGroup.removeView(this._mapboxViewInstance);
415
424
  }
416
- this._accessToken = settings.accessToken;
417
- let context = Application.android.context;
418
- if (settings.context) {
419
- context = settings.context;
420
- }
421
- // Per the Mapbox Android Native samples:
422
- //
423
- // "Mapbox access token is configured here. This needs to be called either in your application
424
- // object or in the same activity which contains the mapview."
425
- com.mapbox.mapboxsdk.Mapbox.getInstance(context, this._accessToken);
426
- const mapboxMapOptions = this._getMapboxMapOptions(settings);
427
- // unlike the Mapbox Android Native samples, we are not laying the map out
428
- // using the Android XML layout features. Instead, we are creating the map
429
- // programmatically.
430
- this._mapboxViewInstance = new com.mapbox.mapboxsdk.maps.MapView(context, mapboxMapOptions);
431
- // required per the Mapbox Android API.
432
- this._mapboxViewInstance.onCreate(null);
433
- // define some listeners to inform in case the map does not
434
- // load.
435
- if (Trace.isEnabled()) {
436
- this.onDidFailLoadingMapListener = new com.mapbox.mapboxsdk.maps.MapView.OnDidFailLoadingMapListener({
437
- onDidFailLoadingMap: (error) => CLog(CLogTypes.error, 'Mapbox::show(): failed to load map:', error)
438
- });
439
- this._mapboxViewInstance.addOnDidFailLoadingMapListener(this.onDidFailLoadingMapListener);
440
- }
441
- if (Trace.isEnabled()) {
442
- this.onDidFinishLoadingMapListener = new com.mapbox.mapboxsdk.maps.MapView.OnDidFinishLoadingMapListener({
443
- onDidFinishLoadingMap: () => CLog(CLogTypes.info, 'show(): finished loading map')
444
- });
445
- this._mapboxViewInstance.addOnDidFinishLoadingMapListener(this.onDidFinishLoadingMapListener);
446
- }
447
- this.onMapReadyCallback = new com.mapbox.mapboxsdk.maps.OnMapReadyCallback({
448
- onMapReady: (mbMap) => {
449
- this._mapboxMapInstance = mbMap;
425
+ }
426
+ this._accessToken = settings.accessToken;
427
+ let context = Utils.android.getApplicationContext();
428
+ if (settings.context) {
429
+ context = settings.context;
430
+ }
431
+ const mapboxMapOptions = this._getMapboxMapOptions(context, settings);
432
+ // unlike the Mapbox Android Native samples, we are not laying the map out
433
+ // using the Android XML layout features. Instead, we are creating the map
434
+ // programmatically.
435
+ this._mapboxViewInstance = new com.mapbox.maps.MapView(context, mapboxMapOptions);
436
+ // define some listeners to inform in case the map does not
437
+ // load.
438
+ this._mapboxMapInstance = this._mapboxViewInstance.getMapboxMap();
439
+ const gesturePlugin = this._getGesturesPlugin();
440
+ gesturePlugin.setPitchEnabled(!settings.disableTilt);
441
+ gesturePlugin.setScrollEnabled(!settings.disableScroll);
442
+ gesturePlugin.setRotateEnabled(!settings.disableRotation);
443
+ gesturePlugin.setPinchToZoomDecelerationEnabled(!settings.disableZoom);
444
+ const attributionPlugin = this._getPlugin('MAPBOX_ATTRIBUTION_PLUGIN_ID');
445
+ attributionPlugin.setEnabled(!settings.hideAttribution);
446
+ attributionPlugin.setPosition(Mapbox.mapPositionToGravity(settings.attributionPosition));
447
+ const compassPlugin = this._getPlugin('MAPBOX_COMPASS_PLUGIN_ID');
448
+ compassPlugin.setEnabled(!settings.hideCompass);
449
+ compassPlugin.setPosition(Mapbox.mapPositionToGravity(settings.compassPosition));
450
+ const logoPlugin = this._getPlugin('MAPBOX_LOGO_PLUGIN_ID');
451
+ logoPlugin.setEnabled(!settings.hideLogo);
452
+ logoPlugin.setPosition(Mapbox.mapPositionToGravity(settings.logoPosition));
453
+ if (Trace.isEnabled()) {
454
+ CLog(CLogTypes.info, 'show(): onMapReady() with instance:', this._mapboxMapInstance);
455
+ }
456
+ // Android SDK 7.0.0 and on requires that the style be set separately after the map
457
+ // is initialized. We do not consider the map ready until the style has successfully
458
+ // loaded.
459
+ const mapStyle = this._getMapStyle(settings.style);
460
+ if (Trace.isEnabled()) {
461
+ CLog(CLogTypes.info, 'show(): loadStyleUri:', mapStyle);
462
+ }
463
+ this._mapboxMapInstance.loadStyle(mapStyle, new com.mapbox.maps.Style.OnStyleLoaded({
464
+ onStyleLoaded: (param0) => {
465
+ try {
450
466
  if (Trace.isEnabled()) {
451
- CLog(CLogTypes.info, 'show(): onMapReady() with instance:', this._mapboxMapInstance);
467
+ CLog(CLogTypes.info, 'show(): style loaded.');
452
468
  }
453
- // Android SDK 7.0.0 and on requires that the style be set separately after the map
454
- // is initialized. We do not consider the map ready until the style has successfully
455
- // loaded.
456
- this.setMapStyle(settings.style).then((style) => {
457
- if (Trace.isEnabled()) {
458
- CLog(CLogTypes.info, 'show(): style loaded.');
469
+ // initialize the event handlers now that we have a constructed view.
470
+ this.markerManager = new MarkerManager(this._mapboxMapInstance, this._mapboxViewInstance, (marker) => {
471
+ const cachedMarker = this._getClickedMarkerDetails(marker);
472
+ if (cachedMarker?.onTap) {
473
+ const result = cachedMarker.onTap(cachedMarker);
474
+ return !!result;
459
475
  }
460
- // initialize the event handlers now that we have a constructed view.
461
- this.initEventHandlerShim(settings, this._mapboxViewInstance);
462
- this._addMarkers(settings.markers, this._mapboxViewInstance);
463
- if (settings.showUserLocation) {
464
- this.requestFineLocationPermission()
465
- .then(() => {
466
- this.showUserLocationMarker(settings.locationComponentOptions);
467
- // if we have a callback defined, call it.
468
- if (settings.onLocationPermissionGranted) {
469
- settings.onLocationPermissionGranted(this._mapboxMapInstance);
470
- }
471
- })
472
- .catch((err) => {
473
- if (settings.onLocationPermissionDenied) {
474
- settings.onLocationPermissionDenied(this._mapboxMapInstance);
475
- }
476
- });
476
+ return false;
477
+ }, (marker) => {
478
+ const cachedMarker = this._getClickedMarkerDetails(marker);
479
+ if (cachedMarker?.onCalloutTap) {
480
+ const result = cachedMarker.onCalloutTap(cachedMarker);
481
+ return !!result;
477
482
  }
478
- // if we have an onMapReady callback fire it.
479
- if (settings.onMapReady) {
480
- settings.onMapReady(this._mapboxMapInstance);
483
+ return false;
484
+ });
485
+ this._addMarkers(settings.markers, this._mapboxViewInstance);
486
+ this.initEventHandlerShim(settings, this._mapboxViewInstance);
487
+ const annotationPlugin = this._getPlugin('MAPBOX_ANNOTATION_PLUGIN_ID');
488
+ this.lineManager = annotationPlugin.createAnnotationManager(com.mapbox.maps.plugin.annotation.AnnotationType.PolylineAnnotation, new com.mapbox.maps.plugin.annotation.AnnotationConfig());
489
+ this.onAnnotationClickListener = new com.mapbox.maps.plugin.annotation.generated.OnPolylineAnnotationClickListener({
490
+ onAnnotationClick: (line) => {
491
+ if (Trace.isEnabled()) {
492
+ CLog(CLogTypes.info, 'Mapbox:setMapStyle(): click on line:', line);
493
+ }
494
+ this.handleLineClickEvent(line);
495
+ return true;
481
496
  }
482
- resolve({
483
- android: this._mapboxViewInstance
484
- });
485
497
  });
498
+ this.lineManager.addClickListener(this.onAnnotationClickListener);
499
+ if (settings.showUserLocation) {
500
+ this.requestFineLocationPermission()
501
+ .then(() => {
502
+ this.showUserLocationMarker(settings.locationComponentOptions);
503
+ // if we have a callback defined, call it.
504
+ if (settings.onLocationPermissionGranted) {
505
+ settings.onLocationPermissionGranted(this._mapboxMapInstance);
506
+ }
507
+ })
508
+ .catch((err) => {
509
+ if (settings.onLocationPermissionDenied) {
510
+ settings.onLocationPermissionDenied(this._mapboxMapInstance);
511
+ }
512
+ });
513
+ }
514
+ // if we have an onMapReady callback fire it.
515
+ if (settings.onMapReady) {
516
+ settings.onMapReady(this._mapboxMapInstance, this._mapboxViewInstance);
517
+ }
518
+ resolve({ android: this._mapboxMapInstance, ios: null });
486
519
  }
487
- });
488
- this._mapboxViewInstance.getMapAsync(this.onMapReadyCallback);
520
+ catch (ex) {
521
+ if (Trace.isEnabled()) {
522
+ CLog(CLogTypes.error, 'Error in mapbox.show.loadStyle: ' + ex);
523
+ }
524
+ console.error(ex, ex.stack);
525
+ reject(ex);
526
+ }
527
+ }
528
+ }));
529
+ if (Trace.isEnabled()) {
530
+ CLog(CLogTypes.info, 'show(): after getMapAsync()');
531
+ }
532
+ // we either have been given a view to add the map to or we
533
+ // add it to the top making it full screen.
534
+ if (settings.parentView) {
489
535
  if (Trace.isEnabled()) {
490
- CLog(CLogTypes.info, 'show(): after getMapAsync()');
536
+ CLog(CLogTypes.info, 'show(): adding map to passed in view');
491
537
  }
492
- // we either have been given a view to add the map to or we
493
- // add it to the top making it full screen.
494
- if (settings.parentView) {
495
- if (Trace.isEnabled()) {
496
- CLog(CLogTypes.info, 'show(): adding map to passed in view');
497
- }
498
- settings.parentView.addView(this._mapboxViewInstance);
538
+ settings.parentView.addView(this._mapboxViewInstance);
539
+ }
540
+ else if (settings.container) {
541
+ if (Trace.isEnabled()) {
542
+ CLog(CLogTypes.info, 'show(): adding map to passed in container');
499
543
  }
500
- else if (settings.container) {
501
- if (Trace.isEnabled()) {
502
- CLog(CLogTypes.info, 'show(): adding map to passed in container');
503
- }
504
- // Application.android.currentContext has been removed.
505
- context = Application.android.foregroundActivity;
506
- if (!context) {
507
- context = Application.android.startActivity;
508
- }
509
- const mapViewLayout = new android.widget.FrameLayout(context);
510
- if (Trace.isEnabled()) {
511
- CLog(CLogTypes.info, 'show(): before adding mapboxViewInstance to FrameLayout');
512
- }
513
- mapViewLayout.addView(this._mapboxViewInstance);
514
- if (Trace.isEnabled()) {
515
- CLog(CLogTypes.info, 'show(): before adding FrameLayout to container');
516
- }
517
- settings.container.addChild(mapViewLayout);
544
+ // Application.android.currentContext has been removed.
545
+ context = Application.android.foregroundActivity;
546
+ if (!context) {
547
+ context = Application.android.startActivity;
518
548
  }
549
+ const mapViewLayout = new android.widget.FrameLayout(context);
519
550
  if (Trace.isEnabled()) {
520
- CLog(CLogTypes.info, 'show(): showIt() bottom');
551
+ CLog(CLogTypes.info, 'show(): before adding mapboxViewInstance to FrameLayout');
521
552
  }
522
- };
553
+ mapViewLayout.addView(this._mapboxViewInstance);
554
+ if (Trace.isEnabled()) {
555
+ CLog(CLogTypes.info, 'show(): before adding FrameLayout to container');
556
+ }
557
+ settings.container.addChild(mapViewLayout);
558
+ }
559
+ if (Trace.isEnabled()) {
560
+ CLog(CLogTypes.info, 'show(): showIt() bottom');
561
+ }
562
+ // };
523
563
  // FIXME: There is some initialization error. A short delay works around this.
524
- setTimeout(showIt, settings.delay ? settings.delay : 200);
564
+ // setTimeout(showIt, settings.delay ? settings.delay : 200);
525
565
  }
526
566
  catch (ex) {
527
567
  if (Trace.isEnabled()) {
528
- CLog(CLogTypes.info, 'Error in mapbox.show: ' + ex);
568
+ CLog(CLogTypes.error, 'Error in mapbox.show: ' + ex);
529
569
  }
570
+ console.error(ex, ex.stack);
530
571
  reject(ex);
531
572
  }
532
573
  });
@@ -534,97 +575,125 @@ export class Mapbox extends MapboxCommon {
534
575
  /**
535
576
  * hide the map
536
577
  */
537
- hide() {
538
- return new Promise((resolve, reject) => {
539
- try {
540
- if (this._mapboxViewInstance) {
541
- const viewGroup = this._mapboxViewInstance.getParent();
542
- if (viewGroup !== null) {
543
- viewGroup.setVisibility(android.view.View.INVISIBLE);
544
- }
578
+ async hide() {
579
+ try {
580
+ if (this._mapboxViewInstance) {
581
+ const viewGroup = this._mapboxViewInstance.getParent();
582
+ if (viewGroup !== null) {
583
+ viewGroup.setVisibility(android.view.View.INVISIBLE);
545
584
  }
546
- resolve();
547
585
  }
548
- catch (ex) {
549
- if (Trace.isEnabled()) {
550
- CLog(CLogTypes.info, 'Error in mapbox.hide: ' + ex);
551
- }
552
- reject(ex);
586
+ }
587
+ catch (ex) {
588
+ if (Trace.isEnabled()) {
589
+ CLog(CLogTypes.info, 'Error in mapbox.hide: ' + ex);
553
590
  }
554
- });
591
+ throw ex;
592
+ }
555
593
  }
556
- unhide() {
557
- return new Promise((resolve, reject) => {
558
- try {
559
- if (this._mapboxViewInstance) {
560
- this._mapboxViewInstance.getParent().setVisibility(android.view.View.VISIBLE);
561
- resolve();
562
- }
563
- else {
564
- reject('No map found');
565
- }
594
+ async unhide() {
595
+ try {
596
+ if (this._mapboxViewInstance) {
597
+ this._mapboxViewInstance.getParent().setVisibility(android.view.View.VISIBLE);
566
598
  }
567
- catch (ex) {
568
- if (Trace.isEnabled()) {
569
- CLog(CLogTypes.info, 'Error in mapbox.unhide: ' + ex);
570
- }
571
- reject(ex);
599
+ else {
600
+ throw new Error('No map found');
572
601
  }
573
- });
602
+ }
603
+ catch (ex) {
604
+ if (Trace.isEnabled()) {
605
+ CLog(CLogTypes.info, 'Error in mapbox.unhide: ' + ex);
606
+ }
607
+ throw ex;
608
+ }
574
609
  }
575
610
  /**
576
611
  * destroy the map programmatically
577
612
  *
578
613
  * Destroy the map instance.
579
614
  */
580
- destroy(nativeMap) {
581
- return new Promise(async (resolve, reject) => {
582
- this.clearEventListeners();
583
- this.iconFactory = null;
584
- if (Trace.isEnabled()) {
585
- CLog(CLogTypes.info, 'destroy(): destroying mapbox view.');
586
- }
587
- if (this.lineManager) {
588
- this.lineManager.onDestroy();
589
- this.lineManager = null;
590
- }
591
- if (this.circleManager) {
592
- this.circleManager.onDestroy();
593
- this.circleManager = null;
594
- }
595
- if (this.symbolManager) {
596
- this.symbolManager.onDestroy();
597
- this.symbolManager = null;
598
- }
599
- // if we have a location marker we need to disable it before destroying the map
600
- //
601
- // This is here to prevent a crash. The user code should disable/re-enable the
602
- // location marker.
603
- if (this._locationComponent) {
615
+ clear(nativeMap) {
616
+ this.clearEventListeners();
617
+ this._markerIconDownloadCache = {};
618
+ if (Trace.isEnabled()) {
619
+ CLog(CLogTypes.info, 'destroy(): destroying mapbox view.');
620
+ }
621
+ if (this.lineManager) {
622
+ this.lineManager.onDestroy();
623
+ this.lineManager = null;
624
+ }
625
+ if (this.polygonManager) {
626
+ this.polygonManager.onDestroy();
627
+ this.polygonManager = null;
628
+ }
629
+ if (this.markerManager) {
630
+ this.markerManager.destroy();
631
+ this.markerManager = null;
632
+ }
633
+ // if (this.circleManager) {
634
+ // this.circleManager.onDestroy();
635
+ // this.circleManager = null;
636
+ // }
637
+ // if (this.symbolManager) {
638
+ // this.symbolManager.onDestroy();
639
+ // this.symbolManager = null;
640
+ // }
641
+ // if we have a location marker we need to disable it before destroying the map
642
+ //
643
+ // This is here to prevent a crash. The user code should disable/re-enable the
644
+ // location marker.
645
+ // if (this._locationComponent) {
646
+ // if (Trace.isEnabled()) {
647
+ // CLog(CLogTypes.info, 'destroy(): Location marker not disabled before destroy() called.');
648
+ // }
649
+ const locationPlugin = this._getPlugin('MAPBOX_LOCATION_COMPONENT_PLUGIN_ID');
650
+ locationPlugin.setEnabled(false);
651
+ // }
652
+ if (this._mapboxViewInstance) {
653
+ const viewGroup = this._mapboxViewInstance.getParent();
654
+ if (viewGroup !== null) {
604
655
  if (Trace.isEnabled()) {
605
- CLog(CLogTypes.info, 'destroy(): Location marker not disabled before destroy() called.');
606
- }
607
- await this.hideUserLocationMarker();
608
- }
609
- if (this._mapboxViewInstance) {
610
- const viewGroup = this._mapboxViewInstance.getParent();
611
- if (viewGroup !== null) {
612
- if (Trace.isEnabled()) {
613
- CLog(CLogTypes.info, 'destroy(): removing _mapboxViewInstance view.');
614
- }
615
- viewGroup.removeView(this._mapboxViewInstance);
616
- }
617
- this._mapboxViewInstance.onPause();
618
- this._mapboxViewInstance.onStop();
619
- this._mapboxViewInstance.destroyDrawingCache();
620
- // let the API know that we're programmatically destroying the map.
621
- this._mapboxViewInstance.onDestroy();
622
- this._mapboxViewInstance = null;
623
- this._mapboxMapInstance = null;
624
- }
625
- resolve();
626
- });
627
- }
656
+ CLog(CLogTypes.info, 'destroy(): removing _mapboxViewInstance view.');
657
+ }
658
+ viewGroup.removeView(this._mapboxViewInstance);
659
+ }
660
+ // this._mapboxViewInstance.onPause();
661
+ this._mapboxViewInstance.onStop();
662
+ this._mapboxViewInstance.destroyDrawingCache();
663
+ // let the API know that we're programmatically destroying the map.
664
+ this._mapboxViewInstance.onDestroy();
665
+ this._mapboxViewInstance = null;
666
+ this._mapboxMapInstance = null;
667
+ }
668
+ }
669
+ async destroy(nativeMap) {
670
+ this.clear();
671
+ }
672
+ // private enableUserLocationPlugin() {
673
+ // if (!this.map) {
674
+ // return;
675
+ // }
676
+ // try {
677
+ // const locationPlugin = this.mapView.getPlugin(com.mapbox.maps.plugin.locationcomponent.LocationComponentPlugin.class);
678
+ // locationPlugin.updateSettings((settings: any) => {
679
+ // settings.enabled = this._showUserLocation;
680
+ // if (this._showUserLocation) {
681
+ // settings.puckBearingEnabled = true;
682
+ // settings.locationPuck = com.mapbox.maps.plugin.LocationPuck2D.builder()
683
+ // .bearingImage(
684
+ // com.mapbox.maps.plugin.locationcomponent.ImageHolder.fromDrawable(
685
+ // this._context // you may need context
686
+ // /* your drawable resource id */
687
+ // )
688
+ // )
689
+ // .build();
690
+ // }
691
+ // return settings;
692
+ // });
693
+ // } catch (e) {
694
+ // console.log('Error enabling user location plugin:', e);
695
+ // }
696
+ // }
628
697
  /**
629
698
  * Clear Event Listeners
630
699
  *
@@ -634,70 +703,80 @@ export class Mapbox extends MapboxCommon {
634
703
  * idea to remove these handlers explicitly.
635
704
  */
636
705
  clearEventListeners() {
637
- if (this.onDidFailLoadingMapListener) {
638
- this._mapboxViewInstance.removeOnDidFailLoadingMapListener(this.onDidFailLoadingMapListener);
639
- this.onDidFailLoadingMapListener = null;
640
- }
641
- if (this.onDidFinishLoadingMapListener) {
642
- this._mapboxViewInstance.removeOnDidFinishLoadingMapListener(this.onDidFinishLoadingMapListener);
643
- this.onDidFinishLoadingMapListener = null;
644
- }
645
- if (this.onDidFinishLoadingStyleListener) {
646
- this._mapboxViewInstance.removeOnDidFinishLoadingStyleListener(this.onDidFinishLoadingStyleListener);
647
- this.onDidFinishLoadingStyleListener = null;
648
- }
649
- if (this.onAnnotationClickListener) {
706
+ // if (this.onDidFailLoadingMapListener) {
707
+ // this._mapboxViewInstance.removeOnDidFailLoadingMapListener(this.onDidFailLoadingMapListener);
708
+ // this.onDidFailLoadingMapListener = null;
709
+ // }
710
+ // if (this.onDidFinishLoadingMapListener) {
711
+ // this._mapboxViewInstance.removeOnDidFinishLoadingMapListener(this.onDidFinishLoadingMapListener);
712
+ // this.onDidFinishLoadingMapListener = null;
713
+ // }
714
+ // if (this.onDidFinishLoadingStyleListener) {
715
+ // this._mapboxViewInstance.removeOnDidFinishLoadingStyleListener(this.onDidFinishLoadingStyleListener);
716
+ // this.onDidFinishLoadingStyleListener = null;
717
+ // }
718
+ if (this.onIndicatorPositionChangedListener) {
719
+ const locationPlugin = this._getPlugin('MAPBOX_LOCATION_COMPONENT_PLUGIN_ID');
720
+ locationPlugin.removeOnIndicatorPositionChangedListener(this.onIndicatorPositionChangedListener);
721
+ this.onIndicatorPositionChangedListener = null;
722
+ }
723
+ if (this.onAnnotationClickListener && this.lineManager) {
650
724
  this.lineManager.removeClickListener(this.onAnnotationClickListener);
651
725
  this.onAnnotationClickListener = null;
652
726
  }
653
- if (this.onMarkerClickListener) {
654
- this._mapboxMapInstance.setOnMarkerClickListener(null);
655
- this.onMarkerClickListener = null;
656
- }
657
- if (this.onInfoWindowClickListener) {
658
- this._mapboxMapInstance.setOnInfoWindowClickListener(null);
659
- this.onInfoWindowClickListener = null;
660
- }
661
- if (this.onDidFailLoadingMapListener) {
662
- this._mapboxViewInstance.removeOnDidFailLoadingMapListener(this.onDidFailLoadingMapListener);
663
- this.onDidFailLoadingMapListener = null;
664
- }
727
+ // if (this.onMarkerClickListener) {
728
+ // this._mapboxMapInstance.setOnMarkerClickListener(null);
729
+ // this.onMarkerClickListener = null;
730
+ // }
731
+ // if (this.onInfoWindowClickListener) {
732
+ // this._mapboxMapInstance.setOnInfoWindowClickListener(null);
733
+ // this.onInfoWindowClickListener = null;
734
+ // }
735
+ // if (this.onDidFailLoadingMapListener) {
736
+ // this._mapboxViewInstance.removeOnDidFailLoadingMapListener(this.onDidFailLoadingMapListener);
737
+ // this.onDidFailLoadingMapListener = null;
738
+ // }
665
739
  if (this.onMapClickListener) {
666
- this._mapboxMapInstance.removeOnMapClickListener(this.onMapClickListener);
740
+ com.mapbox.maps.plugin.gestures.GesturesUtils.removeOnMapClickListener(this._mapboxMapInstance, this.onMapClickListener);
667
741
  this.onMapClickListener = null;
668
742
  }
669
743
  if (this.onMapLongClickListener) {
670
- this._mapboxMapInstance.removeOnMapLongClickListener(this.onMapLongClickListener);
744
+ com.mapbox.maps.plugin.gestures.GesturesUtils.removeOnMapLongClickListener(this._mapboxMapInstance, this.onMapLongClickListener);
671
745
  this.onMapLongClickListener = null;
672
746
  }
673
- if (this.onMoveListener) {
674
- this._mapboxMapInstance.removeOnMoveListener(this.onMoveListener);
675
- this.onMoveListener = null;
747
+ if (this.onMoveBeginListener) {
748
+ com.mapbox.maps.plugin.gestures.GesturesUtils.removeOnMoveListener(this._mapboxMapInstance, this.onMoveBeginListener);
749
+ this.onMoveBeginListener = null;
750
+ }
751
+ if (this.onMoveEndListener) {
752
+ com.mapbox.maps.plugin.gestures.GesturesUtils.removeOnMoveListener(this._mapboxMapInstance, this.onMoveEndListener);
753
+ this.onMoveEndListener = null;
676
754
  }
677
755
  if (this.onScrollListener) {
678
- this._mapboxMapInstance.removeOnMoveListener(this.onScrollListener);
756
+ com.mapbox.maps.plugin.gestures.GesturesUtils.removeOnMoveListener(this._mapboxMapInstance, this.onScrollListener);
679
757
  this.onScrollListener = null;
680
758
  }
681
759
  if (this.onFlingListener) {
682
- this._mapboxMapInstance.removeOnFlingListener(this.onFlingListener);
760
+ com.mapbox.maps.plugin.gestures.GesturesUtils.removeOnFlingListener(this._mapboxMapInstance, this.onFlingListener);
683
761
  this.onFlingListener = null;
684
762
  }
763
+ // const cameraPlugin = this._getPlugin<com.mapbox.maps.plugin.animation.CameraAnimationsPlugin>("MAPBOX_CAMERA_PLUGIN_ID");
685
764
  if (this.onCameraMoveListener) {
686
- this._mapboxMapInstance.removeOnCameraMoveListener(this.onCameraMoveListener);
765
+ this.onCameraMoveListener.cancel();
687
766
  this.onCameraMoveListener = null;
688
767
  }
689
- if (this.onCameraMoveCancelListener) {
690
- this._mapboxMapInstance.removeOnCameraMoveCancelListener(this.onCameraMoveCancelListener);
691
- this.onCameraMoveCancelListener = null;
692
- }
693
- if (this.onCameraIdleListener) {
694
- this._mapboxMapInstance.removeOnCameraIdleListener(this.onCameraIdleListener);
695
- this.onCameraIdleListener = null;
696
- }
697
- if (this.onLocationClickListener) {
698
- this._locationComponent.removeOnLocationClickListener(this.onLocationClickListener);
699
- this.onLocationClickListener = null;
768
+ // if (this.onCameraMoveCancelListener) {
769
+ // cameraPlugin.removeOnCameraMoveCancelListener(this.onCameraMoveCancelListener);
770
+ // this.onCameraMoveCancelListener = null;
771
+ // }
772
+ if (this.onMapIdleListener) {
773
+ this.onMapIdleListener.cancel();
774
+ this.onMapIdleListener = null;
700
775
  }
776
+ // if (this.onLocationClickListener) {
777
+ // this._locationComponent.removeOnLocationClickListener(this.onLocationClickListener);
778
+ // this.onLocationClickListener = null;
779
+ // }
701
780
  }
702
781
  // ------------------------------------------------
703
782
  // Life Cycle Hooks
@@ -708,30 +787,30 @@ export class Mapbox extends MapboxCommon {
708
787
  }
709
788
  this._mapboxViewInstance.onStart();
710
789
  }
711
- async onResume(nativeMapViewInstance) {
712
- if (Trace.isEnabled()) {
713
- CLog(CLogTypes.info, 'onResume()');
714
- }
715
- this._mapboxViewInstance.onResume();
716
- }
717
- async onPause(nativeMapViewInstance) {
718
- if (Trace.isEnabled()) {
719
- CLog(CLogTypes.info, 'onPause()');
720
- }
721
- this._mapboxViewInstance.onPause();
722
- }
790
+ // async onResume(nativeMapViewInstance?: any) {
791
+ // if (Trace.isEnabled()) {
792
+ // CLog(CLogTypes.info, 'onResume()');
793
+ // }
794
+ // this._mapboxViewInstance.onResume();
795
+ // }
796
+ // async onPause(nativeMapViewInstance?: any) {
797
+ // if (Trace.isEnabled()) {
798
+ // CLog(CLogTypes.info, 'onPause()');
799
+ // }
800
+ // this._mapboxViewInstance.onPause();
801
+ // }
723
802
  async onStop(nativeMap) {
724
803
  if (Trace.isEnabled()) {
725
804
  CLog(CLogTypes.info, 'onStop()');
726
805
  }
727
806
  this._mapboxViewInstance.onStop();
728
807
  }
729
- async onLowMemory(nativeMap) {
730
- if (Trace.isEnabled()) {
731
- CLog(CLogTypes.info, 'onLowMemory()');
732
- }
733
- this._mapboxViewInstance.onLowMemory();
734
- }
808
+ // async onLowMemory(nativeMap?: any) {
809
+ // if (Trace.isEnabled()) {
810
+ // CLog(CLogTypes.info, 'onLowMemory()');
811
+ // }
812
+ // this._mapboxViewInstance.onLowMemory();
813
+ // }
735
814
  async onDestroy(nativeMap) {
736
815
  if (Trace.isEnabled()) {
737
816
  CLog(CLogTypes.info, 'onDestroy()');
@@ -838,51 +917,25 @@ export class Mapbox extends MapboxCommon {
838
917
  * an invoke any registered callbacks.
839
918
  */
840
919
  handleLineClickEvent(clickOverlay) {
841
- const lineEntry = this.lines.find((entry) => {
842
- if (Trace.isEnabled()) {
843
- CLog(CLogTypes.info, "Mapbox:handleLineClickEvent(): checking lineEntry clickOverlay id '" + entry.clickOverlay + "' against clickOverlay '" + clickOverlay + "'");
844
- }
845
- return entry.clickOverlay === clickOverlay;
846
- });
847
- if (!lineEntry) {
920
+ const lineEntryId = Object.keys(this._polylines).find((key) => this._polylines[key] === clickOverlay);
921
+ if (!lineEntryId) {
848
922
  console.error('Mapbox:handleLineClick(): click on overlay without an underlying line layer');
849
923
  return false;
850
924
  }
851
925
  for (let x = 0; x < this.eventCallbacks['click'].length; x++) {
852
926
  const entry = this.eventCallbacks['click'][x];
853
927
  if (Trace.isEnabled()) {
854
- CLog(CLogTypes.info, "Mapbox:handleLineClickEvent(): checking entry id '" + entry.id + "' against lineEnty id '" + lineEntry.id + "'");
928
+ CLog(CLogTypes.info, "Mapbox:handleLineClickEvent(): checking entry id '" + entry.id + "' against lineEnty id '" + lineEntryId + "'");
855
929
  }
856
- if (entry.id === lineEntry.id) {
930
+ if (entry.id === lineEntryId) {
857
931
  if (Trace.isEnabled()) {
858
932
  CLog(CLogTypes.info, "Mapbox:handleLineClickEvent(): calling callback for '" + entry.id + "'");
859
933
  }
860
- return entry.callback(lineEntry);
934
+ return entry.callback({ id: lineEntryId, android: clickOverlay });
861
935
  }
862
936
  } // end of for loop over events.
863
937
  return false;
864
938
  }
865
- hasFineLocationPermission() {
866
- return new Promise((resolve, reject) => {
867
- try {
868
- resolve(this._fineLocationPermissionGranted());
869
- }
870
- catch (ex) {
871
- if (Trace.isEnabled()) {
872
- CLog(CLogTypes.info, 'Error in mapbox.hasFineLocationPermission: ' + ex);
873
- }
874
- reject(ex);
875
- }
876
- });
877
- }
878
- /**
879
- * Request fine locaion permission
880
- *
881
- * @link https://docs.mapbox.com/android/core/overview/#permissionsmanager
882
- */
883
- async requestFineLocationPermission() {
884
- return request('location');
885
- }
886
939
  /**
887
940
  * set the map style
888
941
  *
@@ -892,12 +945,12 @@ export class Mapbox extends MapboxCommon {
892
945
  * NOTE: The style must be explicitly set using this method in the onMapReady() handler.
893
946
  *
894
947
  * @param {string | MapStyle } style - a style following the Mapbox style specification or a URL to a style.
895
- * @param {any} nativeMapViewInstance - native map view (com.mapbox.mapboxsdk.maps.MapView)
948
+ * @param {any} nativeMapViewInstance - native map view (com.mapbox.maps.MapView)
896
949
  *
897
950
  * @see MapboxViewCommonBase:setMapStyle()
898
951
  *
899
952
  * @link https://docs.mapbox.com/android/api/map-sdk/7.1.2/com/mapbox/mapboxsdk/maps/Style.Builder.html
900
- * @link https://docs.mapbox.com/android/api/map-sdk/7.1.2/com/mapbox/mapboxsdk/maps/MapboxMap.html#setStyle-java.lang.String-com.mapbox.mapboxsdk.maps.Style.OnStyleLoaded-
953
+ * @link https://docs.mapbox.com/android/api/map-sdk/7.1.2/com/mapbox/mapboxsdk/maps/MapboxMap.html#setStyle-java.lang.String-com.mapbox.maps.Style.OnStyleLoaded-
901
954
  */
902
955
  setMapStyle(style, nativeMapViewInstance) {
903
956
  return new Promise((resolve, reject) => {
@@ -906,57 +959,14 @@ export class Mapbox extends MapboxCommon {
906
959
  if (Trace.isEnabled()) {
907
960
  CLog(CLogTypes.info, 'setMapStyle(): with style:', style);
908
961
  }
909
- // callback for when the style is successfully loaded.
910
- this.onDidFinishLoadingStyleListener = new com.mapbox.mapboxsdk.maps.MapView.OnDidFinishLoadingStyleListener({
911
- onDidFinishLoadingStyle: () => {
962
+ this._mapboxMapInstance.loadStyle(mapStyle, new com.mapbox.maps.Style.OnStyleLoaded({
963
+ onStyleLoaded: (param0) => {
912
964
  if (Trace.isEnabled()) {
913
965
  CLog(CLogTypes.info, 'Mapbox:setMapStyle(): style loaded');
914
966
  }
915
- // FIXME: now that the map is initialized and the style is loaded we can
916
- // create the annotation managers that allow us to (hopefully) reliably
917
- // receive events on lines
918
- const nMapbox = this._mapboxMapInstance;
919
- const nMapView = this._mapboxViewInstance;
920
- const nStyle = nMapbox.getStyle();
921
- this.lineManager = new com.mapbox.mapboxsdk.plugins.annotation.LineManager(nMapView, nMapbox, nStyle);
922
- // this.symbolManager = new com.mapbox.mapboxsdk.plugins.annotation.SymbolManager(nMapView, nMapbox, nStyle);
923
- // this.symbolManager.addClickListener(
924
- // new com.mapbox.mapboxsdk.plugins.annotation.OnSymbolClickListener({
925
- // onAnnotationClick: (marker: com.mapbox.mapboxsdk.plugins.annotation.Symbol) => {
926
- // const cachedMarker = this._getClickedMarkerDetails(marker);
927
- // if (cachedMarker && cachedMarker.onTap) {
928
- // cachedMarker.onTap(cachedMarker);
929
- // }
930
- // return false;
931
- // },
932
- // })
933
- // );
934
- this.onAnnotationClickListener = new com.mapbox.mapboxsdk.plugins.annotation.OnAnnotationClickListener({
935
- onAnnotationClick: (line) => {
936
- if (Trace.isEnabled()) {
937
- CLog(CLogTypes.info, 'Mapbox:setMapStyle(): click on line:', line);
938
- }
939
- this.handleLineClickEvent(line);
940
- return true;
941
- }
942
- });
943
- this.lineManager.addClickListener(this.onAnnotationClickListener);
944
967
  resolve();
945
968
  }
946
- });
947
- this._mapboxViewInstance.addOnDidFinishLoadingStyleListener(this.onDidFinishLoadingStyleListener);
948
- // callback if loading the style fails.
949
- this.onDidFailLoadingMapListener = new com.mapbox.mapboxsdk.maps.MapView.OnDidFailLoadingMapListener({
950
- onDidFailLoadingMap: (error) => {
951
- if (Trace.isEnabled()) {
952
- CLog(CLogTypes.error, 'Mapbox:setMapStyle(): style failed', mapStyle, error);
953
- }
954
- reject(error);
955
- }
956
- });
957
- this._mapboxViewInstance.addOnDidFailLoadingMapListener(this.onDidFailLoadingMapListener);
958
- const builder = new com.mapbox.mapboxsdk.maps.Style.Builder();
959
- this._mapboxMapInstance.setStyle(builder.fromUri(mapStyle));
969
+ }));
960
970
  }
961
971
  catch (ex) {
962
972
  if (Trace.isEnabled()) {
@@ -1028,17 +1038,27 @@ export class Mapbox extends MapboxCommon {
1028
1038
  }
1029
1039
  });
1030
1040
  }
1041
+ /**
1042
+ *
1043
+ * @deprecated
1044
+ * @link https://github.com/mapbox/mapbox-plugins-android/tree/master/plugin-annotation
1045
+ */
1031
1046
  async addMarkers(markers, nativeMap) {
1032
1047
  try {
1033
- this._addMarkers(markers, this._mapboxViewInstance);
1048
+ await this._addMarkers(markers, this._mapboxViewInstance);
1034
1049
  }
1035
1050
  catch (ex) {
1036
1051
  if (Trace.isEnabled()) {
1037
- CLog(CLogTypes.info, 'Error in mapbox.addMarkers: ' + ex);
1052
+ CLog(CLogTypes.error, 'Error in mapbox.addMarkers: ' + ex + ex.stack);
1038
1053
  }
1039
1054
  throw ex;
1040
1055
  }
1041
1056
  }
1057
+ /**
1058
+ *
1059
+ * @deprecated
1060
+ * @link https://github.com/mapbox/mapbox-plugins-android/tree/master/plugin-annotation
1061
+ */
1042
1062
  async removeMarkers(ids, nativeMap) {
1043
1063
  try {
1044
1064
  this._removeMarkers(ids, this._mapboxViewInstance);
@@ -1050,146 +1070,124 @@ export class Mapbox extends MapboxCommon {
1050
1070
  throw ex;
1051
1071
  }
1052
1072
  }
1053
- /**
1054
- *
1055
- * @deprecated
1056
- * @link https://github.com/mapbox/mapbox-plugins-android/tree/master/plugin-annotation
1057
- */
1058
- _addMarkers(markers, nativeMap) {
1073
+ async _addMarkers(markers, nativeMap) {
1059
1074
  if (!markers) {
1060
1075
  if (Trace.isEnabled()) {
1061
- CLog(CLogTypes.info, 'No markers passed');
1076
+ CLog(CLogTypes.error, 'No markers passed');
1062
1077
  }
1063
1078
  return;
1064
1079
  }
1065
1080
  if (!Array.isArray(markers)) {
1066
1081
  if (Trace.isEnabled()) {
1067
- CLog(CLogTypes.info, "markers must be passed as an Array: [{title:'foo'}]");
1082
+ CLog(CLogTypes.error, "markers must be passed as an Array: [{title:'foo'}]");
1068
1083
  }
1069
1084
  return;
1070
1085
  }
1071
1086
  if (!this._mapboxMapInstance) {
1072
1087
  return;
1073
1088
  }
1074
- if (!this.onMarkerClickListener) {
1075
- this.onMarkerClickListener = new com.mapbox.mapboxsdk.maps.MapboxMap.OnMarkerClickListener({
1076
- onMarkerClick: (marker) => {
1077
- const cachedMarker = this._getClickedMarkerDetails(marker);
1078
- if (cachedMarker && cachedMarker.onTap) {
1079
- cachedMarker.onTap(cachedMarker);
1080
- }
1081
- return false;
1082
- }
1083
- });
1084
- this._mapboxMapInstance.setOnMarkerClickListener(this.onMarkerClickListener);
1085
- }
1086
- if (!this.onInfoWindowClickListener) {
1087
- this.onInfoWindowClickListener = new com.mapbox.mapboxsdk.maps.MapboxMap.OnInfoWindowClickListener({
1088
- onInfoWindowClick: (marker) => {
1089
- const cachedMarker = this._getClickedMarkerDetails(marker);
1090
- if (cachedMarker && cachedMarker.onCalloutTap) {
1091
- cachedMarker.onCalloutTap(cachedMarker);
1092
- }
1093
- return true;
1094
- }
1095
- });
1096
- this._mapboxMapInstance.setOnInfoWindowClickListener(this.onInfoWindowClickListener);
1097
- }
1098
- if (!this.iconFactory) {
1099
- this.iconFactory = com.mapbox.mapboxsdk.annotations.IconFactory.getInstance(Application.android.context);
1100
- }
1101
- const iconFactory = this.iconFactory;
1102
1089
  // if any markers need to be downloaded from the web they need to be available synchronously, so fetch them first before looping
1103
- this._downloadMarkerImages(markers).then((updatedMarkers) => {
1104
- for (const m in updatedMarkers) {
1105
- const marker = updatedMarkers[m];
1106
- this._markers.push(marker);
1107
- const markerOptions = new com.mapbox.mapboxsdk.annotations.MarkerOptions();
1108
- markerOptions.setTitle(marker.title);
1109
- markerOptions.setSnippet(marker.subtitle);
1110
- markerOptions.setPosition(new com.mapbox.mapboxsdk.geometry.LatLng(parseFloat(marker.lat), parseFloat(marker.lng)));
1111
- if (marker.icon) {
1112
- // for markers from url see UrlMarker in https://github.com/mapbox/mapbox-gl-native/issues/5370
1113
- if (marker.icon.startsWith('res://')) {
1114
- let cached = this.iconCache[marker.icon];
1115
- if (!cached) {
1116
- const resourcename = marker.icon.substring(6);
1117
- const res = Utils.ad.getApplicationContext().getResources();
1118
- const identifier = res.getIdentifier(resourcename, 'drawable', Utils.ad.getApplication().getPackageName());
1119
- if (identifier !== 0) {
1120
- cached = this.iconCache[marker.icon] = iconFactory.fromResource(identifier);
1121
- }
1122
- }
1123
- if (cached) {
1124
- markerOptions.setIcon(cached);
1125
- }
1126
- else {
1127
- console.warn(`No icon found for this device density for icon ' ${marker.icon}'. Falling back to the default icon.`);
1090
+ if (Trace.isEnabled()) {
1091
+ CLog(CLogTypes.log, 'adding markers');
1092
+ }
1093
+ const updatedMarkers = await this._downloadMarkerImages(markers);
1094
+ if (Trace.isEnabled()) {
1095
+ CLog(CLogTypes.log, 'adding updatedMarkers: ' + JSON.stringify(updatedMarkers));
1096
+ }
1097
+ for (let index = 0; index < updatedMarkers.length; index++) {
1098
+ const marker = updatedMarkers[index];
1099
+ // const markerOptions = new com.mapbox.maps.annotations.MarkerOptions();
1100
+ // markerOptions.setTitle(marker.title);
1101
+ // markerOptions.setSnippet(marker.subtitle);
1102
+ // markerOptions.setPosition(new com.mapbox.maps.geometry.LatLng(marker.lat, marker.lng));
1103
+ let icon;
1104
+ marker.icon = marker.icon || 'res://ic_red_marker';
1105
+ if (marker.icon) {
1106
+ // for markers from url see UrlMarker in https://github.com/mapbox/mapbox-gl-native/issues/5370
1107
+ if (marker.icon.startsWith(Utils.RESOURCE_PREFIX)) {
1108
+ let cached = this.iconCache[marker.icon];
1109
+ if (!cached) {
1110
+ const bitmap = bitmapFromDrawableResource(marker.icon.substring(Utils.RESOURCE_PREFIX.length));
1111
+ if (bitmap) {
1112
+ cached = this.iconCache[marker.icon] = new ImageSource(bitmap);
1128
1113
  }
1129
1114
  }
1130
- else if (marker.icon.startsWith('http')) {
1131
- if (marker.iconDownloaded !== null) {
1132
- markerOptions.setIcon(iconFactory.fromBitmap(marker.iconDownloaded));
1133
- }
1115
+ if (cached) {
1116
+ icon = cached;
1134
1117
  }
1135
1118
  else {
1136
- if (Trace.isEnabled()) {
1137
- CLog(CLogTypes.info, 'Please use res://resourcename, http(s)://imageurl or iconPath to use a local path');
1138
- }
1119
+ console.warn(`No icon found for this device density for icon ' ${marker.icon}'. Falling back to the default icon.`);
1139
1120
  }
1140
1121
  }
1141
- else if (marker.iconPath) {
1142
- let cached = this.iconCache[marker.iconPath];
1143
- if (!cached) {
1144
- const iconFullPath = path.join(knownFolders.currentApp().path, marker.iconPath.replace('~/', ''));
1145
- // if the file doesn't exist the app will crash, so checking it
1146
- if (File.exists(iconFullPath)) {
1147
- // could set width, height, retina, see https://github.com/Telerik-Verified-Plugins/Mapbox/pull/42/files?diff=unified&short_path=1c65267, but that's what the marker.icon param is for..
1148
- cached = this.iconCache[marker.iconPath] = iconFactory.fromPath(iconFullPath);
1149
- }
1122
+ else if (marker.icon.startsWith('http')) {
1123
+ if (marker.downloadedIcon !== null) {
1124
+ icon = marker.downloadedIcon;
1125
+ // markerOptions.setIcon(iconFactory.fromBitmap(marker.iconDownloaded));
1150
1126
  }
1151
- if (cached) {
1152
- markerOptions.setIcon(cached);
1127
+ }
1128
+ else {
1129
+ if (Trace.isEnabled()) {
1130
+ CLog(CLogTypes.info, 'Please use res://resourcename, http(s)://imageurl or iconPath to use a local path');
1153
1131
  }
1154
- else {
1155
- console.warn(`Marker icon not found, using the default instead. Requested path: '" + ${marker.iconPath}'.`);
1132
+ }
1133
+ }
1134
+ else if (marker.iconPath) {
1135
+ let cached = this.iconCache[marker.iconPath];
1136
+ if (!cached) {
1137
+ const iconFullPath = path.join(knownFolders.currentApp().path, marker.iconPath.replace('~/', ''));
1138
+ // if the file doesn't exist the app will crash, so checking it
1139
+ if (File.exists(iconFullPath)) {
1140
+ // could set width, height, retina, see https://github.com/Telerik-Verified-Plugins/Mapbox/pull/42/files?diff=unified&short_path=1c65267, but that's what the marker.icon param is for..
1141
+ cached = this.iconCache[marker.iconPath] = ImageSource.fromFileSync(iconFullPath);
1156
1142
  }
1157
1143
  }
1158
- marker.android = this._mapboxMapInstance.addMarker(markerOptions);
1159
- if (marker.selected) {
1160
- this._mapboxMapInstance.selectMarker(marker.android);
1144
+ if (cached) {
1145
+ icon = cached;
1161
1146
  }
1162
- marker.update = (newSettings) => {
1163
- for (const m in this._markers) {
1164
- const _marker = this._markers[m];
1165
- if (marker.id === _marker.id) {
1166
- if (newSettings.onTap !== undefined) {
1167
- _marker.onTap = newSettings.onTap;
1168
- }
1169
- if (newSettings.onCalloutTap !== undefined) {
1170
- _marker.onCalloutTap = newSettings.onCalloutTap;
1171
- }
1172
- if (newSettings.title !== undefined) {
1173
- _marker.title = newSettings.title;
1174
- _marker.android.setTitle(newSettings.title);
1175
- }
1176
- if (newSettings.subtitle !== undefined) {
1177
- _marker.subtitle = newSettings.title;
1178
- _marker.android.setSnippet(newSettings.subtitle);
1179
- }
1180
- if (newSettings.lat && newSettings.lng) {
1181
- _marker.lat = newSettings.lat;
1182
- _marker.lng = newSettings.lng;
1183
- _marker.android.setPosition(new com.mapbox.mapboxsdk.geometry.LatLng(parseFloat(newSettings.lat), parseFloat(newSettings.lng)));
1184
- }
1185
- if (newSettings.selected) {
1186
- this._mapboxMapInstance.selectMarker(_marker.android);
1187
- }
1188
- }
1147
+ else {
1148
+ console.warn(`Marker icon not found, using the default instead. Requested path: '" + ${marker.iconPath}'.`);
1149
+ }
1150
+ }
1151
+ marker.android = this.markerManager.addMarker(new AndroidMarker({
1152
+ position: com.mapbox.geojson.Point.fromLngLat(marker.lng, marker.lat),
1153
+ title: marker.title,
1154
+ snippet: marker.subtitle,
1155
+ icon: icon?.android
1156
+ }));
1157
+ this._markers.push(marker);
1158
+ if (marker.selected) {
1159
+ this.markerManager.selectMarker(marker.android);
1160
+ }
1161
+ marker.update = (newSettings) => {
1162
+ console.log('update marker', Object.keys(newSettings), newSettings);
1163
+ const theMarker = this._markers.find((m) => m.id === marker.id);
1164
+ if (theMarker) {
1165
+ if (newSettings.onTap) {
1166
+ theMarker.onTap = newSettings.onTap;
1189
1167
  }
1190
- };
1191
- }
1192
- });
1168
+ if (newSettings.onCalloutTap) {
1169
+ theMarker.onCalloutTap = newSettings.onCalloutTap;
1170
+ }
1171
+ if (newSettings.title) {
1172
+ theMarker.title = newSettings.title;
1173
+ theMarker.android.title = newSettings.title;
1174
+ }
1175
+ if (newSettings.subtitle) {
1176
+ theMarker.subtitle = newSettings.subtitle;
1177
+ theMarker.android.snippet = newSettings.subtitle;
1178
+ }
1179
+ if (newSettings.lat && newSettings.lng) {
1180
+ theMarker.lat = newSettings.lat;
1181
+ theMarker.lng = newSettings.lng;
1182
+ theMarker.android.position = com.mapbox.geojson.Point.fromLngLat(theMarker.lng, theMarker.lat);
1183
+ }
1184
+ this.markerManager.updateMarker(theMarker.android);
1185
+ if (newSettings.selected) {
1186
+ this.markerManager.selectMarker(theMarker.android, false, true);
1187
+ }
1188
+ }
1189
+ };
1190
+ }
1193
1191
  }
1194
1192
  /**
1195
1193
  *
@@ -1199,14 +1197,13 @@ export class Mapbox extends MapboxCommon {
1199
1197
  if (!this._mapboxMapInstance) {
1200
1198
  return;
1201
1199
  }
1202
- for (const m in this._markers) {
1203
- const marker = this._markers[m];
1200
+ this._markers.forEach((marker) => {
1204
1201
  if (!ids || (marker && marker.id && ids.indexOf(marker.id) > -1)) {
1205
1202
  if (marker && marker.android) {
1206
- this._mapboxMapInstance.removeAnnotation(marker.android);
1203
+ this.markerManager.removeMarker(marker.android);
1207
1204
  }
1208
1205
  }
1209
- }
1206
+ });
1210
1207
  // remove markers from cache
1211
1208
  if (ids) {
1212
1209
  this._markers = this._markers.filter((marker) => ids.indexOf(marker.id) === -1);
@@ -1218,13 +1215,13 @@ export class Mapbox extends MapboxCommon {
1218
1215
  setCenter(options, nativeMap) {
1219
1216
  return new Promise((resolve, reject) => {
1220
1217
  try {
1221
- const cameraPosition = new com.mapbox.mapboxsdk.camera.CameraPosition.Builder().target(new com.mapbox.mapboxsdk.geometry.LatLng(options.lat, options.lng)).build();
1218
+ const cameraPosition = new com.mapbox.maps.CameraOptions.Builder().center(com.mapbox.geojson.Point.fromLngLat(options.lng, options.lat)).build();
1222
1219
  if (options.animated === true) {
1223
- const newCameraPosition = com.mapbox.mapboxsdk.camera.CameraUpdateFactory.newCameraPosition(cameraPosition);
1224
- this._mapboxMapInstance.animateCamera(newCameraPosition, 1000, null);
1220
+ const animationOptions = new com.mapbox.maps.plugin.animation.MapAnimationOptions.Builder().duration(1000).build();
1221
+ com.nativescript.mapbox.Camera.flyTo(this._mapboxViewInstance, cameraPosition, animationOptions, null);
1225
1222
  }
1226
1223
  else {
1227
- this._mapboxMapInstance.setCameraPosition(cameraPosition);
1224
+ this._mapboxMapInstance.setCamera(cameraPosition);
1228
1225
  }
1229
1226
  resolve();
1230
1227
  }
@@ -1239,10 +1236,10 @@ export class Mapbox extends MapboxCommon {
1239
1236
  getCenter(nativeMap) {
1240
1237
  return new Promise((resolve, reject) => {
1241
1238
  try {
1242
- const coordinate = this._mapboxMapInstance.getCameraPosition().target;
1239
+ const coordinate = this._mapboxMapInstance.getCameraState().getCenter();
1243
1240
  resolve({
1244
- lat: coordinate.getLatitude(),
1245
- lng: coordinate.getLongitude()
1241
+ lat: coordinate.latitude(),
1242
+ lng: coordinate.longitude()
1246
1243
  });
1247
1244
  }
1248
1245
  catch (ex) {
@@ -1259,12 +1256,13 @@ export class Mapbox extends MapboxCommon {
1259
1256
  const animated = options.animated === undefined || options.animated;
1260
1257
  const level = options.level;
1261
1258
  if (level >= 0 && level <= 20) {
1262
- const cameraUpdate = com.mapbox.mapboxsdk.camera.CameraUpdateFactory.zoomTo(level);
1259
+ const cameraPosition = new com.mapbox.maps.CameraOptions.Builder().zoom(java.lang.Double.valueOf(level)).build();
1263
1260
  if (animated) {
1264
- this._mapboxMapInstance.easeCamera(cameraUpdate);
1261
+ const animationOptions = new com.mapbox.maps.plugin.animation.MapAnimationOptions.Builder().build();
1262
+ com.nativescript.mapbox.Camera.flyTo(this._mapboxViewInstance, cameraPosition, animationOptions, null);
1265
1263
  }
1266
1264
  else {
1267
- this._mapboxMapInstance.moveCamera(cameraUpdate);
1265
+ this._mapboxMapInstance.setCamera(cameraPosition);
1268
1266
  }
1269
1267
  resolve();
1270
1268
  }
@@ -1283,7 +1281,7 @@ export class Mapbox extends MapboxCommon {
1283
1281
  getZoomLevel(nativeMap) {
1284
1282
  return new Promise((resolve, reject) => {
1285
1283
  try {
1286
- const level = this._mapboxMapInstance.getCameraPosition().zoom;
1284
+ const level = this._mapboxMapInstance.getCameraState().getZoom();
1287
1285
  resolve(level);
1288
1286
  }
1289
1287
  catch (ex) {
@@ -1298,13 +1296,21 @@ export class Mapbox extends MapboxCommon {
1298
1296
  return new Promise((resolve, reject) => {
1299
1297
  try {
1300
1298
  const tilt = options.tilt ? options.tilt : 30;
1301
- const cameraPositionBuilder = new com.mapbox.mapboxsdk.camera.CameraPosition.Builder().tilt(tilt);
1302
- const cameraUpdate = com.mapbox.mapboxsdk.camera.CameraUpdateFactory.newCameraPosition(cameraPositionBuilder.build());
1303
- const durationMs = options.duration ? options.duration : 5000;
1304
- this._mapboxMapInstance.easeCamera(cameraUpdate, durationMs);
1305
- setTimeout(() => {
1299
+ const cameraPosition = new com.mapbox.maps.CameraOptions.Builder().pitch(java.lang.Double.valueOf(tilt)).build();
1300
+ const animated = options.animated === undefined || options.animated;
1301
+ if (animated) {
1302
+ const animationOptions = new com.mapbox.maps.plugin.animation.MapAnimationOptions.Builder().duration(options.duration ? options.duration : 5000).build();
1303
+ com.nativescript.mapbox.Camera.flyTo(this._mapboxViewInstance, cameraPosition, animationOptions, new android.animation.Animator.AnimatorListener({
1304
+ onAnimationCancel: () => resolve(),
1305
+ onAnimationEnd: () => resolve(),
1306
+ onAnimationStart: () => { },
1307
+ onAnimationRepeat: () => { }
1308
+ }));
1309
+ }
1310
+ else {
1311
+ this._mapboxMapInstance.setCamera(cameraPosition);
1306
1312
  resolve();
1307
- }, durationMs);
1313
+ }
1308
1314
  }
1309
1315
  catch (ex) {
1310
1316
  if (Trace.isEnabled()) {
@@ -1317,7 +1323,7 @@ export class Mapbox extends MapboxCommon {
1317
1323
  getTilt(nativeMap) {
1318
1324
  return new Promise((resolve, reject) => {
1319
1325
  try {
1320
- const tilt = this._mapboxMapInstance.getCameraPosition().tilt;
1326
+ const tilt = this._mapboxMapInstance.getCameraState().getPitch();
1321
1327
  resolve(tilt);
1322
1328
  }
1323
1329
  catch (ex) {
@@ -1336,12 +1342,18 @@ export class Mapbox extends MapboxCommon {
1336
1342
  getUserLocation() {
1337
1343
  return new Promise((resolve, reject) => {
1338
1344
  try {
1339
- const loc = this._locationComponent ? this._locationComponent.getLastKnownLocation() : null;
1340
- if (loc === null) {
1345
+ // const locationPlugin = this._getPlugin<com.mapbox.maps.plugin.locationcomponent.LocationComponentPlugin>("MAPBOX_LOCATION_COMPONENT_PLUGIN_ID");
1346
+ // const loc = this._locationComponent ? this._locationComponent.getLastKnownLocation() : null;
1347
+ if (this.lastKnownLocation === null) {
1341
1348
  reject('Location not available');
1342
1349
  }
1343
1350
  else {
1344
- resolve(_getLocation(loc));
1351
+ resolve({
1352
+ location: {
1353
+ lat: this.lastKnownLocation.latitude(),
1354
+ lng: this.lastKnownLocation.longitude()
1355
+ }
1356
+ });
1345
1357
  }
1346
1358
  }
1347
1359
  catch (ex) {
@@ -1362,24 +1374,36 @@ export class Mapbox extends MapboxCommon {
1362
1374
  reject("Please set the 'point' parameter");
1363
1375
  return;
1364
1376
  }
1377
+ if (!this._mapboxMapInstance) {
1378
+ reject('No map has been loaded');
1379
+ return;
1380
+ }
1365
1381
  if (!options) {
1366
1382
  options = {};
1367
1383
  }
1368
- const mapboxPoint = new com.mapbox.mapboxsdk.geometry.LatLng(options.point.lat, options.point.lng);
1369
- const screenLocation = this._mapboxMapInstance.getProjection().toScreenLocation(mapboxPoint);
1370
- if (this._mapboxMapInstance.queryRenderedFeatures) {
1371
- const queryFilter = options.filter ? ExpressionParser.parseJson(options.filter) : null;
1372
- const features = this._mapboxMapInstance.queryRenderedFeatures(screenLocation, queryFilter, options.layers);
1373
- const result = [];
1374
- for (let i = 0; i < features.size(); i++) {
1375
- const feature = features.get(i);
1376
- result.push(JSON.parse(feature.toJson()));
1377
- }
1378
- resolve(result);
1379
- }
1380
- else {
1381
- reject('Feature not supported by this Mapbox version');
1384
+ if (Trace.isEnabled()) {
1385
+ CLog(CLogTypes.info, 'Mapbox:queryRenderedFeatures(): ', JSON.stringify(options));
1382
1386
  }
1387
+ const mapboxPoint = com.mapbox.geojson.Point.fromLngLat(options.point.lng, options.point.lat);
1388
+ const screenLocation = this._mapboxMapInstance.pixelForCoordinate(mapboxPoint);
1389
+ const queryFilter = options.filter ? ExpressionParser.parseJson(options.filter) : null;
1390
+ const queryOptions = new com.mapbox.maps.RenderedQueryOptions(java.util.Arrays.asList(options.layers), queryFilter);
1391
+ this._mapboxMapInstance.queryRenderedFeatures(com.mapbox.maps.RenderedQueryGeometry.valueOf(screenLocation), queryOptions, new com.mapbox.maps.QueryRenderedFeaturesCallback({
1392
+ run: (result) => {
1393
+ if (result.isError()) {
1394
+ reject(new Error(result.getError()));
1395
+ }
1396
+ else {
1397
+ const features = result.getValue();
1398
+ const jsFeatures = [];
1399
+ for (let i = 0; i < features.size(); i++) {
1400
+ const feature = features.get(i);
1401
+ jsFeatures.push(JSON.parse(feature.getQueriedFeature().getFeature().toJson()));
1402
+ }
1403
+ resolve(jsFeatures);
1404
+ }
1405
+ }
1406
+ }));
1383
1407
  }
1384
1408
  catch (ex) {
1385
1409
  if (Trace.isEnabled()) {
@@ -1395,30 +1419,34 @@ export class Mapbox extends MapboxCommon {
1395
1419
  if (!options) {
1396
1420
  options = {};
1397
1421
  }
1398
- const source = this._mapboxMapInstance.getStyle().getSource(sourceId);
1422
+ const source = this.getSource(sourceId);
1399
1423
  if (!source) {
1400
1424
  throw new Error(`Source with id "${sourceId}" not found.`);
1401
1425
  }
1402
- let features;
1403
1426
  const queryFilter = options.filter ? ExpressionParser.parseJson(options.filter) : null;
1404
- if (source instanceof com.mapbox.mapboxsdk.style.sources.GeoJsonSource) {
1405
- features = source.querySourceFeatures(queryFilter);
1406
- }
1407
- else if (source instanceof com.mapbox.mapboxsdk.style.sources.VectorSource) {
1408
- if (!options.sourceLayer) {
1409
- throw new Error('The option "sourceLayer" is required for vector sources.');
1427
+ this._mapboxMapInstance.querySourceFeatures(sourceId, new com.mapbox.maps.SourceQueryOptions(null, // source layer IDs
1428
+ queryFilter), new com.mapbox.maps.QuerySourceFeaturesCallback({
1429
+ run(result) {
1430
+ if (result.isError()) {
1431
+ reject(new Error(result.getError()));
1432
+ }
1433
+ else {
1434
+ const lineFeatures = result.getValue();
1435
+ if (lineFeatures.size() === 0) {
1436
+ reject(new Error('no line string feature found'));
1437
+ }
1438
+ else {
1439
+ const features = result.getValue();
1440
+ const jsFeatures = [];
1441
+ for (let i = 0; i < features.size(); i++) {
1442
+ const feature = features.get(i);
1443
+ jsFeatures.push(JSON.parse(feature.getQueriedFeature().getFeature().toJson()));
1444
+ }
1445
+ resolve(jsFeatures);
1446
+ }
1447
+ }
1410
1448
  }
1411
- features = source.querySourceFeatures([options.sourceLayer], queryFilter);
1412
- }
1413
- else {
1414
- throw new Error('Only sources from type "vector" or "geojson" are supported.');
1415
- }
1416
- const result = [];
1417
- for (let i = 0; i < features.size(); i++) {
1418
- const feature = features.get(i);
1419
- result.push(JSON.parse(feature.toJson()));
1420
- }
1421
- resolve(result);
1449
+ }));
1422
1450
  }
1423
1451
  catch (ex) {
1424
1452
  if (Trace.isEnabled()) {
@@ -1440,21 +1468,21 @@ export class Mapbox extends MapboxCommon {
1440
1468
  reject("Please set the 'points' parameter");
1441
1469
  return;
1442
1470
  }
1443
- const polygonOptions = new com.mapbox.mapboxsdk.annotations.PolygonOptions();
1444
- for (const p in points) {
1445
- const point = points[p];
1446
- polygonOptions.add(new com.mapbox.mapboxsdk.geometry.LatLng(point.lat, point.lng));
1471
+ if (!this.polygonManager) {
1472
+ const annotationPlugin = this._getPlugin('MAPBOX_ANNOTATION_PLUGIN_ID');
1473
+ this.polygonManager = annotationPlugin.createAnnotationManager(com.mapbox.maps.plugin.annotation.AnnotationType.PolygonAnnotation, new com.mapbox.maps.plugin.annotation.AnnotationConfig());
1447
1474
  }
1448
- polygonOptions.fillColor(Mapbox.getAndroidColor(options.fillColor));
1449
- polygonOptions.alpha(options.fillOpacity === undefined ? 1 : options.fillOpacity);
1475
+ const polygonOptions = new com.mapbox.maps.plugin.annotation.generated.PolygonAnnotationOptions();
1476
+ const nPoints = java.util.Arrays.asList([java.util.Arrays.asList(points.map((p) => com.mapbox.geojson.Point.fromLngLat(p.lng, p.lat)))]);
1477
+ console.log('add points', nPoints);
1478
+ polygonOptions.withPoints(nPoints);
1479
+ polygonOptions.withFillColor(Mapbox.getAndroidColor(options.fillColor));
1480
+ polygonOptions.withFillOpacity(options.fillOpacity === undefined ? 1 : options.fillOpacity);
1450
1481
  // Note that the stroke is barely visible, see https://github.com/mapbox/mapbox-gl-native/issues/5676
1451
1482
  if (options.strokeColor) {
1452
- polygonOptions.strokeColor(Mapbox.getAndroidColor(options.strokeColor));
1483
+ polygonOptions.withFillOutlineColor(Mapbox.getAndroidColor(options.strokeColor));
1453
1484
  }
1454
- this._polygons.push({
1455
- id: options.id || new Date().getTime(),
1456
- android: this._mapboxMapInstance.addPolygon(polygonOptions)
1457
- });
1485
+ this._polylines[options.id || new Date().getTime()] = this.polygonManager.create(polygonOptions);
1458
1486
  resolve();
1459
1487
  }
1460
1488
  catch (ex) {
@@ -1477,18 +1505,16 @@ export class Mapbox extends MapboxCommon {
1477
1505
  reject("Please set the 'points' parameter");
1478
1506
  return;
1479
1507
  }
1480
- const polylineOptions = new com.mapbox.mapboxsdk.annotations.PolylineOptions();
1481
- polylineOptions.width(options.width || 5); // default 5
1482
- polylineOptions.color(Mapbox.getAndroidColor(options.color));
1483
- polylineOptions.alpha(options.opacity === undefined ? 1 : options.opacity);
1484
- for (const p in points) {
1485
- const point = points[p];
1486
- polylineOptions.add(new com.mapbox.mapboxsdk.geometry.LatLng(point.lat, point.lng));
1487
- }
1488
- this._polylines.push({
1489
- id: options.id || new Date().getTime(),
1490
- android: this._mapboxMapInstance.addPolyline(polylineOptions)
1491
- });
1508
+ if (!this.lineManager) {
1509
+ const annotationPlugin = this._getPlugin('MAPBOX_ANNOTATION_PLUGIN_ID');
1510
+ this.lineManager = annotationPlugin.createAnnotationManager(com.mapbox.maps.plugin.annotation.AnnotationType.PolylineAnnotation, new com.mapbox.maps.plugin.annotation.AnnotationConfig());
1511
+ }
1512
+ const polylineOptions = new com.mapbox.maps.plugin.annotation.generated.PolylineAnnotationOptions();
1513
+ polylineOptions.withLineWidth(options.width || 5); // default 5
1514
+ polylineOptions.withLineColor(Mapbox.getAndroidColor(options.color));
1515
+ polylineOptions.withLineOpacity(options.opacity === undefined ? 1 : options.opacity);
1516
+ polylineOptions.withPoints(java.util.Arrays.asList(points.map((p) => com.mapbox.geojson.Point.fromLngLat(p.lng, p.lat))));
1517
+ this._polylines[options.id || new Date().getTime()] = this.lineManager.create(polylineOptions);
1492
1518
  resolve();
1493
1519
  }
1494
1520
  catch (ex) {
@@ -1502,12 +1528,16 @@ export class Mapbox extends MapboxCommon {
1502
1528
  removePolygons(ids, nativeMap) {
1503
1529
  return new Promise((resolve, reject) => {
1504
1530
  try {
1505
- for (const p in this._polygons) {
1506
- const polygon = this._polygons[p];
1507
- if (!ids || (polygon.id && ids.indexOf(polygon.id) > -1)) {
1508
- this._mapboxMapInstance.removePolygon(polygon.android);
1531
+ if (!ids) {
1532
+ this.polygonManager.deleteAll();
1533
+ this._polygons = {};
1534
+ }
1535
+ ids.forEach((id) => {
1536
+ if (this._polygons[id]) {
1537
+ this.polygonManager.delete(this._polygons[id]);
1538
+ delete this._polygons[id];
1509
1539
  }
1510
- }
1540
+ });
1511
1541
  resolve();
1512
1542
  }
1513
1543
  catch (ex) {
@@ -1521,12 +1551,16 @@ export class Mapbox extends MapboxCommon {
1521
1551
  removePolylines(ids, nativeMap) {
1522
1552
  return new Promise((resolve, reject) => {
1523
1553
  try {
1524
- for (const p in this._polylines) {
1525
- const polyline = this._polylines[p];
1526
- if (!ids || (polyline.id && ids.indexOf(polyline.id) > -1)) {
1527
- this._mapboxMapInstance.removePolyline(polyline.android);
1554
+ if (!ids) {
1555
+ this.lineManager.deleteAll();
1556
+ this._polylines = {};
1557
+ }
1558
+ ids.forEach((id) => {
1559
+ if (this._polylines[id]) {
1560
+ this.lineManager.delete(this._polylines[id]);
1561
+ delete this._polylines[id];
1528
1562
  }
1529
- }
1563
+ });
1530
1564
  resolve();
1531
1565
  }
1532
1566
  catch (ex) {
@@ -1545,12 +1579,19 @@ export class Mapbox extends MapboxCommon {
1545
1579
  const padding = options.padding || 0;
1546
1580
  const defaultPadding = 0;
1547
1581
  // ensure padding is an object and assign default values
1548
- const { top = defaultPadding, left = defaultPadding, bottom = defaultPadding, right = defaultPadding } = typeof padding === 'object' ? padding : { top: padding, left: padding, bottom: padding, right: padding };
1549
- const bounds = new com.mapbox.mapboxsdk.geometry.LatLngBounds.Builder()
1550
- .include(new com.mapbox.mapboxsdk.geometry.LatLng(options.bounds.north, options.bounds.east))
1551
- .include(new com.mapbox.mapboxsdk.geometry.LatLng(options.bounds.south, options.bounds.west))
1552
- .build();
1553
- this._mapboxMapInstance.animateCamera(com.mapbox.mapboxsdk.camera.CameraUpdateFactory.newLatLngBounds(bounds, left, top, right, bottom), durationMs, null);
1582
+ const { bottom = defaultPadding, left = defaultPadding, right = defaultPadding, top = defaultPadding } = typeof padding === 'object' ? padding : { top: padding, left: padding, bottom: padding, right: padding };
1583
+ const cameraForBounds = this._mapboxMapInstance.cameraForCoordinates(java.util.Arrays.asList([
1584
+ com.mapbox.geojson.Point.fromLngLat(options.bounds.west, options.bounds.north),
1585
+ com.mapbox.geojson.Point.fromLngLat(options.bounds.east, options.bounds.south)
1586
+ ]), new com.mapbox.maps.EdgeInsets(top, left, bottom, right), java.lang.Double.valueOf(options.bearing ?? 0), // bearing
1587
+ java.lang.Double.valueOf(options.tilt ?? 0) // pitch
1588
+ );
1589
+ const cameraOptionsBuilder = new com.mapbox.maps.CameraOptions.Builder();
1590
+ cameraOptionsBuilder.center(cameraForBounds.getCenter());
1591
+ cameraOptionsBuilder.zoom(cameraForBounds.getZoom());
1592
+ cameraOptionsBuilder.bearing(cameraForBounds.getBearing());
1593
+ cameraOptionsBuilder.pitch(cameraForBounds.getPitch());
1594
+ com.nativescript.mapbox.Camera.flyTo(this._mapboxViewInstance, cameraOptionsBuilder.build(), new com.mapbox.maps.plugin.animation.MapAnimationOptions.Builder().duration(durationMs).build(), null);
1554
1595
  }
1555
1596
  else {
1556
1597
  const target = options.target;
@@ -1558,17 +1599,18 @@ export class Mapbox extends MapboxCommon {
1558
1599
  reject("Please set the 'target' parameter");
1559
1600
  return;
1560
1601
  }
1561
- const cameraPositionBuilder = new com.mapbox.mapboxsdk.camera.CameraPosition.Builder(this._mapboxMapInstance.getCameraPosition()).target(new com.mapbox.mapboxsdk.geometry.LatLng(target.lat, target.lng));
1602
+ const cameraOptionsBuilder = new com.mapbox.maps.CameraOptions.Builder();
1603
+ cameraOptionsBuilder.center(com.mapbox.geojson.Point.fromLngLat(target.lng, target.lat));
1562
1604
  if (options.bearing) {
1563
- cameraPositionBuilder.bearing(options.bearing);
1605
+ cameraOptionsBuilder.bearing(java.lang.Double.valueOf(options.bearing));
1564
1606
  }
1565
1607
  if (options.tilt) {
1566
- cameraPositionBuilder.tilt(options.tilt);
1608
+ cameraOptionsBuilder.pitch(java.lang.Double.valueOf(options.tilt));
1567
1609
  }
1568
1610
  if (options.zoomLevel) {
1569
- cameraPositionBuilder.zoom(options.zoomLevel);
1611
+ cameraOptionsBuilder.zoom(java.lang.Double.valueOf(options.zoomLevel));
1570
1612
  }
1571
- this._mapboxMapInstance.animateCamera(com.mapbox.mapboxsdk.camera.CameraUpdateFactory.newCameraPosition(cameraPositionBuilder.build()), durationMs, null);
1613
+ com.nativescript.mapbox.Camera.flyTo(this._mapboxViewInstance, cameraOptionsBuilder.build(), new com.mapbox.maps.plugin.animation.MapAnimationOptions.Builder().duration(durationMs).build(), null);
1572
1614
  }
1573
1615
  setTimeout(() => {
1574
1616
  resolve();
@@ -1582,14 +1624,6 @@ export class Mapbox extends MapboxCommon {
1582
1624
  }
1583
1625
  });
1584
1626
  }
1585
- /**
1586
- * set an on map click listener.
1587
- *
1588
- * The new Mapbox Native SDK allows for multiple listeners on an event and follows the standard
1589
- * pattern of returning 'true' when a handler has handled the event and others shouldn't.
1590
- *
1591
- * Not returning a boolean from the listener function will cause a crash.
1592
- */
1593
1627
  setOnMapClickListener(listener, nativeMap) {
1594
1628
  return new Promise((resolve, reject) => {
1595
1629
  try {
@@ -1597,23 +1631,23 @@ export class Mapbox extends MapboxCommon {
1597
1631
  reject('No map has been loaded');
1598
1632
  return;
1599
1633
  }
1600
- this.onMapClickListener = new com.mapbox.mapboxsdk.maps.MapboxMap.OnMapClickListener({
1634
+ this.onMapClickListener = new com.mapbox.maps.plugin.gestures.OnMapClickListener({
1601
1635
  onMapClick: (point) => {
1602
1636
  if (Trace.isEnabled()) {
1603
1637
  CLog(CLogTypes.info, 'Mapbox:setOnMapClickListener(): click event at point:', point);
1604
1638
  }
1605
- return listener({
1606
- lat: point.getLatitude(),
1607
- lng: point.getLongitude()
1639
+ return this.checkForClickEvent({
1640
+ lat: point.latitude(),
1641
+ lng: point.longitude()
1608
1642
  });
1609
1643
  }
1610
1644
  });
1611
- this._mapboxMapInstance.addOnMapClickListener(this.onMapClickListener);
1645
+ com.mapbox.maps.plugin.gestures.GesturesUtils.addOnMapClickListener(this._mapboxMapInstance, this.onMapClickListener);
1612
1646
  resolve();
1613
1647
  }
1614
1648
  catch (ex) {
1615
1649
  if (Trace.isEnabled()) {
1616
- CLog(CLogTypes.info, 'Error in mapbox.setOnMapClickListener: ' + ex);
1650
+ CLog(CLogTypes.info, 'Error in mapbox.setOnMapLongClickListener: ' + ex);
1617
1651
  }
1618
1652
  reject(ex);
1619
1653
  }
@@ -1626,13 +1660,13 @@ export class Mapbox extends MapboxCommon {
1626
1660
  reject('No map has been loaded');
1627
1661
  return;
1628
1662
  }
1629
- this.onMapLongClickListener = new com.mapbox.mapboxsdk.maps.MapboxMap.OnMapLongClickListener({
1663
+ this.onMapLongClickListener = new com.mapbox.maps.plugin.gestures.OnMapLongClickListener({
1630
1664
  onMapLongClick: (point) => listener({
1631
- lat: point.getLatitude(),
1632
- lng: point.getLongitude()
1665
+ lat: point.latitude(),
1666
+ lng: point.longitude()
1633
1667
  })
1634
1668
  });
1635
- this._mapboxMapInstance.addOnMapLongClickListener(this.onMapLongClickListener);
1669
+ this._getGesturesPlugin().addOnMapLongClickListener(this.onMapLongClickListener);
1636
1670
  resolve();
1637
1671
  }
1638
1672
  catch (ex) {
@@ -1653,18 +1687,18 @@ export class Mapbox extends MapboxCommon {
1653
1687
  if (Trace.isEnabled()) {
1654
1688
  CLog(CLogTypes.info, 'setOnMoveBeginListener():');
1655
1689
  }
1656
- this.onMoveListener = new com.mapbox.mapboxsdk.maps.MapboxMap.OnMoveListener({
1657
- onMoveBegin: (detector /* MoveGestureDetector */) => {
1658
- const coordinate = this._mapboxMapInstance.getCameraPosition().target;
1690
+ this.onMoveBeginListener = new com.mapbox.maps.plugin.gestures.OnMoveListener({
1691
+ onMoveBegin: (detector) => {
1692
+ const coordinate = this._mapboxMapInstance.getCameraState().getCenter();
1659
1693
  return listener({
1660
- lat: coordinate.getLatitude(),
1661
- lng: coordinate.getLongitude()
1694
+ lat: coordinate.latitude(),
1695
+ lng: coordinate.longitude()
1662
1696
  });
1663
1697
  },
1664
- onMove: (detector /* MoveGestureDetector */) => { },
1665
- onMoveEnd: (detector /* MoveGestureDetector */) => { }
1698
+ onMove: (detector) => false,
1699
+ onMoveEnd: (detector) => { }
1666
1700
  });
1667
- this._mapboxMapInstance.addOnMoveListener(this.onMoveListener);
1701
+ com.mapbox.maps.plugin.gestures.GesturesUtils.addOnMoveListener(this._mapboxMapInstance, this.onMoveBeginListener);
1668
1702
  resolve();
1669
1703
  }
1670
1704
  catch (ex) {
@@ -1685,18 +1719,18 @@ export class Mapbox extends MapboxCommon {
1685
1719
  if (Trace.isEnabled()) {
1686
1720
  CLog(CLogTypes.info, 'setOnMoveEndListener():');
1687
1721
  }
1688
- this.onMoveListener = new com.mapbox.mapboxsdk.maps.MapboxMap.OnMoveListener({
1722
+ this.onMoveEndListener = new com.mapbox.maps.plugin.gestures.OnMoveListener({
1689
1723
  onMoveBegin: (detector /* MoveGestureDetector */) => { },
1690
- onMove: (detector /* MoveGestureDetector */) => { },
1724
+ onMove: (detector) => false,
1691
1725
  onMoveEnd: (detector /* MoveGestureDetector */) => {
1692
- const coordinate = this._mapboxMapInstance.getCameraPosition().target;
1726
+ const coordinate = this._mapboxMapInstance.getCameraState().getCenter();
1693
1727
  return listener({
1694
- lat: coordinate.getLatitude(),
1695
- lng: coordinate.getLongitude()
1728
+ lat: coordinate.latitude(),
1729
+ lng: coordinate.longitude()
1696
1730
  });
1697
1731
  }
1698
1732
  });
1699
- this._mapboxMapInstance.addOnMoveListener(this.onMoveListener);
1733
+ com.mapbox.maps.plugin.gestures.GesturesUtils.addOnMoveListener(this._mapboxMapInstance, this.onMoveEndListener);
1700
1734
  resolve();
1701
1735
  }
1702
1736
  catch (ex) {
@@ -1718,18 +1752,19 @@ export class Mapbox extends MapboxCommon {
1718
1752
  CLog(CLogTypes.info, 'setOnScrollListener():');
1719
1753
  }
1720
1754
  // the 'onMove' event seems like the one closest to the iOS implementation
1721
- this.onScrollListener = new com.mapbox.mapboxsdk.maps.MapboxMap.OnMoveListener({
1755
+ this.onScrollListener = new com.mapbox.maps.plugin.gestures.OnMoveListener({
1722
1756
  onMoveBegin: (detector /* MoveGestureDetector */) => { },
1723
1757
  onMove: (detector /* MoveGestureDetector */) => {
1724
- const coordinate = this._mapboxMapInstance.getCameraPosition().target;
1725
- return listener({
1726
- lat: coordinate.getLatitude(),
1727
- lng: coordinate.getLongitude()
1758
+ const coordinate = this._mapboxMapInstance.getCameraState().getCenter();
1759
+ listener({
1760
+ lat: coordinate.latitude(),
1761
+ lng: coordinate.longitude()
1728
1762
  });
1763
+ return false;
1729
1764
  },
1730
1765
  onMoveEnd: (detector /* MoveGestureDetector */) => { }
1731
1766
  });
1732
- this._mapboxMapInstance.addOnMoveListener(this.onScrollListener);
1767
+ com.mapbox.maps.plugin.gestures.GesturesUtils.addOnMoveListener(this._mapboxMapInstance, this.onScrollListener);
1733
1768
  resolve();
1734
1769
  }
1735
1770
  catch (ex) {
@@ -1747,10 +1782,10 @@ export class Mapbox extends MapboxCommon {
1747
1782
  reject('No map has been loaded');
1748
1783
  return;
1749
1784
  }
1750
- this.onFlingListener = new com.mapbox.mapboxsdk.maps.MapboxMap.OnFlingListener({
1785
+ this.onFlingListener = new com.mapbox.maps.plugin.gestures.OnFlingListener({
1751
1786
  onFling: () => listener()
1752
1787
  });
1753
- this._mapboxMapInstance.addOnFlingListener(this.onFlingListener);
1788
+ this._getGesturesPlugin().addOnFlingListener(this.onFlingListener);
1754
1789
  resolve();
1755
1790
  }
1756
1791
  catch (ex) {
@@ -1761,17 +1796,18 @@ export class Mapbox extends MapboxCommon {
1761
1796
  }
1762
1797
  });
1763
1798
  }
1764
- setOnCameraMoveListener(listener, nativeMap) {
1799
+ setOnCameraChangeListener(listener, nativeMap) {
1765
1800
  return new Promise((resolve, reject) => {
1766
1801
  try {
1767
1802
  if (!this._mapboxMapInstance) {
1768
1803
  reject('No map has been loaded');
1769
1804
  return;
1770
1805
  }
1771
- this.onCameraMoveListener = new com.mapbox.mapboxsdk.maps.MapboxMap.OnCameraMoveListener({
1772
- onCameraMove: () => listener(0, false)
1773
- });
1774
- this._mapboxMapInstance.addOnCameraMoveListener(this.onCameraMoveListener);
1806
+ this.onCameraMoveListener = this._mapboxMapInstance.subscribeCameraChanged(new com.mapbox.maps.CameraChangedCallback({
1807
+ run(param) {
1808
+ listener(0, false);
1809
+ }
1810
+ }));
1775
1811
  resolve();
1776
1812
  }
1777
1813
  catch (ex) {
@@ -1784,36 +1820,19 @@ export class Mapbox extends MapboxCommon {
1784
1820
  }
1785
1821
  setOnCameraMoveCancelListener(listener, nativeMap) {
1786
1822
  return new Promise((resolve, reject) => {
1787
- try {
1788
- if (!this._mapboxMapInstance) {
1789
- reject('No map has been loaded');
1790
- return;
1791
- }
1792
- this.onCameraMoveCancelListener = new com.mapbox.mapboxsdk.maps.MapboxMap.OnCameraMoveCanceledListener({
1793
- onCameraMoveCanceled: () => listener()
1794
- });
1795
- this._mapboxMapInstance.addOnCameraMoveCancelListener(this.onCameraMoveCancelListener);
1796
- resolve();
1797
- }
1798
- catch (ex) {
1799
- if (Trace.isEnabled()) {
1800
- CLog(CLogTypes.info, 'Error in mapbox.setOnCameraMoveCancelListener: ' + ex);
1801
- }
1802
- reject(ex);
1803
- }
1823
+ reject('No conCameraMoveCancel event');
1804
1824
  });
1805
1825
  }
1806
- setOnCameraIdleListener(listener, nativeMap) {
1826
+ setOnMapIdleListener(listener, nativeMap) {
1807
1827
  return new Promise((resolve, reject) => {
1808
1828
  try {
1809
1829
  if (!this._mapboxMapInstance) {
1810
1830
  reject('No map has been loaded');
1811
1831
  return;
1812
1832
  }
1813
- this.onCameraIdleListener = new com.mapbox.mapboxsdk.maps.MapboxMap.OnCameraIdleListener({
1814
- onCameraIdle: () => listener()
1815
- });
1816
- this._mapboxMapInstance.addOnCameraIdleListener(this.onCameraIdleListener);
1833
+ this.onMapIdleListener = this._mapboxMapInstance.subscribeMapIdle(new com.mapbox.maps.MapIdleCallback({
1834
+ run: () => listener()
1835
+ }));
1817
1836
  resolve();
1818
1837
  }
1819
1838
  catch (ex) {
@@ -1824,31 +1843,38 @@ export class Mapbox extends MapboxCommon {
1824
1843
  }
1825
1844
  });
1826
1845
  }
1827
- getViewport(nativeMap) {
1828
- return new Promise((resolve, reject) => {
1829
- try {
1830
- if (!this._mapboxMapInstance) {
1831
- reject('No map has been loaded');
1832
- return;
1833
- }
1834
- const bounds = this._mapboxMapInstance.getProjection().getVisibleRegion().latLngBounds;
1835
- resolve({
1836
- bounds: {
1837
- north: bounds.getLatNorth(),
1838
- east: bounds.getLonEast(),
1839
- south: bounds.getLatSouth(),
1840
- west: bounds.getLonWest()
1841
- },
1842
- zoomLevel: this._mapboxMapInstance.getCameraPosition().zoom
1843
- });
1844
- }
1845
- catch (ex) {
1846
- if (Trace.isEnabled()) {
1847
- CLog(CLogTypes.info, 'Error in mapbox.getViewport: ' + ex);
1848
- }
1849
- reject(ex);
1846
+ async getViewport(nativeMap) {
1847
+ // return new Promise((resolve, reject) => {
1848
+ try {
1849
+ if (!this._mapboxMapInstance) {
1850
+ throw new Error('No map has been loaded');
1851
+ }
1852
+ const cameraState = this._mapboxMapInstance.getCameraState();
1853
+ // Get the screen coordinate bounds
1854
+ // Get the map view size
1855
+ const width = this._mapboxViewInstance.getWidth();
1856
+ const height = this._mapboxViewInstance.getHeight();
1857
+ // Top-left (NW)
1858
+ const nw = this._mapboxMapInstance.coordinateForPixel(new com.mapbox.maps.ScreenCoordinate(0, 0));
1859
+ // Bottom-right (SE)
1860
+ const se = this._mapboxMapInstance.coordinateForPixel(new com.mapbox.maps.ScreenCoordinate(width, height));
1861
+ return {
1862
+ bounds: {
1863
+ north: nw.latitude(),
1864
+ east: se.longitude(),
1865
+ south: se.latitude(),
1866
+ west: nw.longitude()
1867
+ },
1868
+ zoomLevel: cameraState.getZoom()
1869
+ };
1870
+ }
1871
+ catch (ex) {
1872
+ if (Trace.isEnabled()) {
1873
+ CLog(CLogTypes.info, 'Error in mapbox.getViewport: ' + ex);
1850
1874
  }
1851
- });
1875
+ throw ex;
1876
+ }
1877
+ // });
1852
1878
  }
1853
1879
  setViewport(options, nativeMap) {
1854
1880
  return new Promise((resolve, reject) => {
@@ -1857,22 +1883,29 @@ export class Mapbox extends MapboxCommon {
1857
1883
  reject('No map has been loaded');
1858
1884
  return;
1859
1885
  }
1860
- const bounds = new com.mapbox.mapboxsdk.geometry.LatLngBounds.Builder()
1861
- .include(new com.mapbox.mapboxsdk.geometry.LatLng(options.bounds.north, options.bounds.east))
1862
- .include(new com.mapbox.mapboxsdk.geometry.LatLng(options.bounds.south, options.bounds.west))
1863
- .build();
1864
1886
  const defaultPadding = 25;
1865
1887
  const padding = options.padding ?? defaultPadding;
1866
1888
  const animated = options.animated === undefined || options.animated;
1867
1889
  const durationMs = animated ? 1000 : 0;
1868
1890
  // ensure padding is an object and assign default values
1869
- const { top = defaultPadding, left = defaultPadding, bottom = defaultPadding, right = defaultPadding } = typeof padding === 'object' ? padding : { top: padding, left: padding, bottom: padding, right: padding };
1870
- const cameraUpdate = com.mapbox.mapboxsdk.camera.CameraUpdateFactory.newLatLngBounds(bounds, left, top, right, bottom);
1891
+ const { bottom = defaultPadding, left = defaultPadding, right = defaultPadding, top = defaultPadding } = typeof padding === 'object' ? padding : { top: padding, left: padding, bottom: padding, right: padding };
1892
+ const cameraForBounds = this._mapboxMapInstance.cameraForCoordinates(java.util.Arrays.asList([
1893
+ com.mapbox.geojson.Point.fromLngLat(options.bounds.west, options.bounds.north),
1894
+ com.mapbox.geojson.Point.fromLngLat(options.bounds.east, options.bounds.south)
1895
+ ]), new com.mapbox.maps.EdgeInsets(top, left, bottom, right), java.lang.Double.valueOf(0), // bearing
1896
+ java.lang.Double.valueOf(0) // pitch
1897
+ );
1898
+ const cameraOptionsBuilder = new com.mapbox.maps.CameraOptions.Builder();
1899
+ cameraOptionsBuilder.center(cameraForBounds.getCenter());
1900
+ cameraOptionsBuilder.zoom(cameraForBounds.getZoom());
1901
+ cameraOptionsBuilder.bearing(cameraForBounds.getBearing());
1902
+ cameraOptionsBuilder.pitch(cameraForBounds.getPitch());
1903
+ const cameraOptions = cameraOptionsBuilder.build();
1871
1904
  if (animated) {
1872
- this._mapboxMapInstance.easeCamera(cameraUpdate, durationMs);
1905
+ com.nativescript.mapbox.Camera.flyTo(this._mapboxViewInstance, cameraOptions, new com.mapbox.maps.plugin.animation.MapAnimationOptions.Builder().duration(durationMs).build(), null);
1873
1906
  }
1874
1907
  else {
1875
- this._mapboxMapInstance.moveCamera(cameraUpdate);
1908
+ this._mapboxMapInstance.setCamera(cameraOptions);
1876
1909
  }
1877
1910
  setTimeout(() => {
1878
1911
  resolve();
@@ -1889,65 +1922,84 @@ export class Mapbox extends MapboxCommon {
1889
1922
  downloadOfflineRegion(options) {
1890
1923
  return new Promise((resolve, reject) => {
1891
1924
  try {
1892
- const styleURL = this._getMapStyle(options.style);
1893
- const bounds = new com.mapbox.mapboxsdk.geometry.LatLngBounds.Builder()
1894
- .include(new com.mapbox.mapboxsdk.geometry.LatLng(options.bounds.north, options.bounds.east))
1895
- .include(new com.mapbox.mapboxsdk.geometry.LatLng(options.bounds.south, options.bounds.west))
1896
- .build();
1897
- const retinaFactor = Utils.layout.getDisplayDensity();
1898
- const offlineRegionDefinition = new com.mapbox.mapboxsdk.offline.OfflineTilePyramidRegionDefinition(styleURL, bounds, options.minZoom, options.maxZoom, retinaFactor);
1899
- const info = {
1900
- name: options.name,
1901
- ...options.metadata
1902
- };
1903
- const infoStr = new java.lang.String(JSON.stringify(info));
1904
- const encodedMetadata = infoStr.getBytes();
1905
1925
  if (!this._accessToken && !options.accessToken) {
1906
1926
  reject("First show a map, or pass in an 'accessToken' param");
1907
1927
  return;
1908
1928
  }
1909
1929
  if (!this._accessToken) {
1910
1930
  this._accessToken = options.accessToken;
1911
- com.mapbox.mapboxsdk.Mapbox.getInstance(Application.android.context, this._accessToken);
1931
+ com.mapbox.common.MapboxOptions.setAccessToken(this._accessToken);
1912
1932
  }
1913
- this._getOfflineManager().createOfflineRegion(offlineRegionDefinition, encodedMetadata, new com.mapbox.mapboxsdk.offline.OfflineManager.CreateOfflineRegionCallback({
1914
- onError: (error) => {
1915
- reject(error);
1916
- },
1917
- onCreate: (offlineRegion) => {
1918
- // if (options.onCreate) {
1919
- // options.onCreate(offlineRegion);
1920
- // }
1921
- offlineRegion.setDownloadState(com.mapbox.mapboxsdk.offline.OfflineRegion.STATE_ACTIVE);
1922
- // Monitor the download progress using setObserver
1923
- offlineRegion.setObserver(new com.mapbox.mapboxsdk.offline.OfflineRegion.OfflineRegionObserver({
1924
- onStatusChanged: (status) => {
1925
- // Calculate the download percentage and update the progress bar
1926
- const percentage = status.getRequiredResourceCount() >= 0 ? (100.0 * status.getCompletedResourceCount()) / status.getRequiredResourceCount() : 0.0;
1927
- if (options.onProgress) {
1928
- options.onProgress({
1929
- name: options.name,
1930
- completedSize: status.getCompletedResourceSize(),
1931
- completed: status.getCompletedResourceCount(),
1932
- expected: status.getRequiredResourceCount(),
1933
- percentage: Math.round(percentage * 100) / 100,
1934
- // downloading: status.getDownloadState() == com.mapbox.mapboxsdk.offline.OfflineRegion.STATE_ACTIVE,
1935
- complete: status.isComplete()
1936
- });
1937
- }
1938
- if (status.isComplete()) {
1939
- resolve(status);
1940
- }
1941
- else if (status.isRequiredResourceCountPrecise()) {
1942
- }
1943
- },
1944
- onError: (error) => {
1945
- reject(`${error.getMessage()}, reason: ${error.getReason()}`);
1946
- },
1947
- mapboxTileCountLimitExceeded: (limit) => {
1948
- console.warn(`dl mapboxTileCountLimitExceeded: ${limit}`);
1949
- }
1950
- }));
1933
+ const styleURL = this._getMapStyle(options.style);
1934
+ const regionId = `${options.regionId || Date.now()}`;
1935
+ // Optional: download style pack (the style JSON, sprites, fonts)
1936
+ // const stylePackLoadOptions = new com.mapbox.maps.StylePackLoadOptions.Builder().metadata(Value.fromJson(`{"regionId": "${options.regionId || Date.now()}"}`)).build();
1937
+ const descriptorOptionsBuilder = new com.mapbox.maps.TilesetDescriptorOptions.Builder().styleURI(styleURL);
1938
+ if (options.minZoom !== undefined) {
1939
+ descriptorOptionsBuilder.minZoom(options.minZoom);
1940
+ }
1941
+ if (options.maxZoom !== undefined) {
1942
+ descriptorOptionsBuilder.maxZoom(options.maxZoom);
1943
+ }
1944
+ const descriptorOptions = descriptorOptionsBuilder.build();
1945
+ const tilesetDescriptor = this._getOfflineManager().createTilesetDescriptor(descriptorOptions);
1946
+ const Point = com.mapbox.geojson.Point;
1947
+ const bbox = com.mapbox.geojson.Polygon.fromLngLats(java.util.Arrays.asList([
1948
+ java.util.Arrays.asList([
1949
+ Point.fromLngLat(options.bounds.west, options.bounds.south), // SW
1950
+ Point.fromLngLat(options.bounds.east, options.bounds.south), // SE
1951
+ Point.fromLngLat(options.bounds.east, options.bounds.north), // NE
1952
+ Point.fromLngLat(options.bounds.west, options.bounds.north), // NW
1953
+ Point.fromLngLat(options.bounds.west, options.bounds.south) // close ring
1954
+ ])
1955
+ ]));
1956
+ const info = {
1957
+ name: options.name,
1958
+ regionId,
1959
+ styleUrl: styleURL,
1960
+ minZoom: options.minZoom,
1961
+ maxZoom: options.maxZoom,
1962
+ bounds: options.bounds,
1963
+ ...options.metadata
1964
+ };
1965
+ console.log('downloadRegion', regionId, new com.mapbox.bindgen.Value(JSON.stringify(info)));
1966
+ const regionOptions = new com.mapbox.common.TileRegionLoadOptions.Builder()
1967
+ .geometry(bbox)
1968
+ .descriptors(java.util.Collections.singletonList(tilesetDescriptor))
1969
+ .metadata(new com.mapbox.bindgen.Value(JSON.stringify(info)))
1970
+ .networkRestriction(options['networkRestriction'] ?? com.mapbox.common.NetworkRestriction.NONE)
1971
+ .acceptExpired(options['acceptExpired'] ?? true)
1972
+ .build();
1973
+ this._getTileStore().loadTileRegion(regionId, regionOptions, new com.mapbox.common.TileRegionLoadProgressCallback({
1974
+ run(progress) {
1975
+ const percentage = progress.getRequiredResourceCount() >= 0 ? (100.0 * progress.getCompletedResourceCount()) / progress.getRequiredResourceCount() : 0.0;
1976
+ if (options.onProgress) {
1977
+ options.onProgress({
1978
+ name: options.name,
1979
+ completedSize: progress.getCompletedResourceSize(),
1980
+ completed: progress.getCompletedResourceCount(),
1981
+ expected: progress.getRequiredResourceCount(),
1982
+ percentage: Math.round(percentage * 100) / 100,
1983
+ // downloading: status.getDownloadState() == com.mapbox.maps.offline.OfflineRegion.STATE_ACTIVE,
1984
+ complete: percentage === 1
1985
+ });
1986
+ }
1987
+ }
1988
+ }), new com.mapbox.common.TileRegionCallback({
1989
+ run(expected) {
1990
+ if (expected.isValue()) {
1991
+ // if (options.onProgress) {
1992
+ // options.onProgress({
1993
+ // name: options.name,
1994
+ // percentage: 100,
1995
+ // complete: true
1996
+ // });
1997
+ // }
1998
+ resolve(expected.getValue());
1999
+ }
2000
+ else {
2001
+ reject(expected.getError());
2002
+ }
1951
2003
  }
1952
2004
  }));
1953
2005
  }
@@ -1968,40 +2020,42 @@ export class Mapbox extends MapboxCommon {
1968
2020
  }
1969
2021
  if (!this._accessToken) {
1970
2022
  this._accessToken = options.accessToken;
1971
- com.mapbox.mapboxsdk.Mapbox.getInstance(Application.android.context, this._accessToken);
2023
+ com.mapbox.common.MapboxOptions.setAccessToken(this._accessToken);
1972
2024
  }
1973
- this._getOfflineManager().listOfflineRegions(new com.mapbox.mapboxsdk.offline.OfflineManager.ListOfflineRegionsCallback({
1974
- onError: (error) => {
1975
- reject(error);
1976
- },
1977
- onList: (offlineRegions) => {
1978
- const regions = [];
1979
- if (offlineRegions !== null) {
1980
- for (let i = 0; i < offlineRegions.length; i++) {
1981
- const offlineRegion = offlineRegions[i];
1982
- const name = this._getRegionName(offlineRegion);
1983
- const offlineRegionDefinition = offlineRegion.getDefinition();
1984
- const bounds = offlineRegionDefinition.getBounds();
1985
- const metadata = this._getRegionMetadata(offlineRegion);
1986
- regions.push({
1987
- id: offlineRegion.getID(),
1988
- name,
1989
- style: offlineRegionDefinition.getStyleURL(),
1990
- minZoom: offlineRegionDefinition.getMinZoom(),
1991
- maxZoom: offlineRegionDefinition.getMaxZoom(),
1992
- bounds: {
1993
- north: bounds.getLatNorth(),
1994
- east: bounds.getLonEast(),
1995
- south: bounds.getLatSouth(),
1996
- west: bounds.getLonWest()
1997
- },
1998
- metadata,
1999
- pixelRatio: offlineRegionDefinition.getPixelRatio(),
2000
- type: offlineRegionDefinition.getType()
2001
- });
2025
+ const tileStore = this._getTileStore();
2026
+ tileStore.getAllTileRegions(new com.mapbox.common.TileRegionsCallback({
2027
+ run: async (result) => {
2028
+ try {
2029
+ if (result.isError()) {
2030
+ reject(result.isError());
2002
2031
  }
2032
+ else {
2033
+ const offlineRegions = result.getValue();
2034
+ const regions = [];
2035
+ if (offlineRegions !== null) {
2036
+ for (let i = 0; i < offlineRegions.size(); i++) {
2037
+ const offlineRegion = offlineRegions.get(i);
2038
+ // const bounds = offlineRegionDefinition.getBounds();
2039
+ const { bounds, maxZoom, minZoom, name, regionId, styleUrl, ...metadata } = await this._getRegionMetadata(offlineRegion);
2040
+ regions.push({
2041
+ id: regionId,
2042
+ name,
2043
+ style: styleUrl,
2044
+ minZoom,
2045
+ maxZoom,
2046
+ bounds,
2047
+ metadata
2048
+ // pixelRatio: offlineRegionDefinition.getPixelRatio(),
2049
+ // type: offlineRegionDefinition.getType()
2050
+ });
2051
+ }
2052
+ }
2053
+ resolve(regions);
2054
+ }
2055
+ }
2056
+ catch (error) {
2057
+ reject(error);
2003
2058
  }
2004
- resolve(regions);
2005
2059
  }
2006
2060
  }));
2007
2061
  }
@@ -2020,34 +2074,48 @@ export class Mapbox extends MapboxCommon {
2020
2074
  reject("Pass in the 'id' or 'name' param");
2021
2075
  return;
2022
2076
  }
2023
- this._getOfflineManager().listOfflineRegions(new com.mapbox.mapboxsdk.offline.OfflineManager.ListOfflineRegionsCallback({
2024
- onError: (error) => {
2025
- reject(error);
2026
- },
2027
- onList: (offlineRegions) => {
2028
- const regions = [];
2029
- let found = false;
2030
- if (offlineRegions !== null) {
2031
- for (let i = 0; i < offlineRegions.length; i++) {
2032
- const offlineRegion = offlineRegions[i];
2033
- const regionId = options.id ? offlineRegion.getID() : this._getRegionName(offlineRegion);
2034
- if (regionId === (options.id || options.name)) {
2035
- found = true;
2036
- offlineRegion.delete(new com.mapbox.mapboxsdk.offline.OfflineRegion.OfflineRegionDeleteCallback({
2037
- onError: (error) => {
2038
- reject(error);
2039
- },
2040
- onDelete: () => {
2041
- resolve();
2042
- // don't return, see note below
2077
+ const tileStore = this._getTileStore();
2078
+ tileStore.getAllTileRegions(new com.mapbox.common.TileRegionsCallback({
2079
+ run: async (result) => {
2080
+ try {
2081
+ if (result.isError()) {
2082
+ reject(result.isError());
2083
+ }
2084
+ else {
2085
+ const offlineRegions = result.getValue();
2086
+ let found = false;
2087
+ if (offlineRegions !== null) {
2088
+ for (let i = 0; i < offlineRegions.size(); i++) {
2089
+ const offlineRegion = offlineRegions.get(i);
2090
+ const regionId = options.id ? offlineRegion.getId() : await this._getRegionName(offlineRegion);
2091
+ if (regionId === (options.id || options.name)) {
2092
+ found = true;
2093
+ await new Promise((resolve, reject) => {
2094
+ tileStore.removeTileRegion(offlineRegion.getId(), new com.mapbox.common.TileRegionCallback({
2095
+ run(result) {
2096
+ if (result.isError()) {
2097
+ reject(result.getError());
2098
+ }
2099
+ else {
2100
+ resolve();
2101
+ }
2102
+ }
2103
+ }));
2104
+ });
2105
+ // don't break the loop as there may be multiple packs with the same name
2043
2106
  }
2044
- }));
2045
- // don't break the loop as there may be multiple packs with the same name
2107
+ }
2108
+ }
2109
+ if (!found) {
2110
+ reject('Region not found');
2111
+ }
2112
+ else {
2113
+ resolve();
2046
2114
  }
2047
2115
  }
2048
2116
  }
2049
- if (!found) {
2050
- reject('Region not found');
2117
+ catch (error) {
2118
+ reject(error);
2051
2119
  }
2052
2120
  }
2053
2121
  }));
@@ -2062,25 +2130,32 @@ export class Mapbox extends MapboxCommon {
2062
2130
  }
2063
2131
  _getOfflineManager() {
2064
2132
  if (!this._offlineManager) {
2065
- this._offlineManager = com.mapbox.mapboxsdk.offline.OfflineManager.getInstance(Application.android.context);
2133
+ this._offlineManager = new com.mapbox.maps.OfflineManager();
2066
2134
  }
2067
2135
  return this._offlineManager;
2068
2136
  }
2137
+ _getTileStore() {
2138
+ if (!this._tileStore) {
2139
+ this._tileStore = com.mapbox.common.TileStore.create();
2140
+ }
2141
+ return this._tileStore;
2142
+ }
2069
2143
  addExtrusion(options, nativeMap) {
2070
2144
  return new Promise((resolve, reject) => {
2071
2145
  try {
2072
2146
  // Create fill extrusion layer
2073
- const fillExtrusionLayer = new com.mapbox.mapboxsdk.style.layers.FillExtrusionLayer('3d-buildings', 'composite');
2074
- fillExtrusionLayer.setSourceLayer('building');
2075
- fillExtrusionLayer.setFilter(com.mapbox.mapboxsdk.style.expressions.Expression.eq(com.mapbox.mapboxsdk.style.expressions.Expression.get('extrude'), 'true'));
2076
- fillExtrusionLayer.setMinZoom(15);
2077
- const props = [];
2078
- props[0] = com.mapbox.mapboxsdk.style.layers.PropertyFactory.fillExtrusionColor(android.graphics.Color.LTGRAY);
2079
- props[1] = com.mapbox.mapboxsdk.style.layers.PropertyFactory.fillExtrusionHeight(com.mapbox.mapboxsdk.style.expressions.Expression.get('height'));
2080
- props[2] = com.mapbox.mapboxsdk.style.layers.PropertyFactory.fillExtrusionBase(com.mapbox.mapboxsdk.style.expressions.Expression.get('min_height'));
2081
- props[3] = com.mapbox.mapboxsdk.style.layers.PropertyFactory.fillExtrusionOpacity(com.mapbox.mapboxsdk.style.expressions.Expression.literal(0.6));
2082
- // Set data-driven styling properties
2083
- fillExtrusionLayer.setProperties(props);
2147
+ const fillExtrusionLayer = new com.mapbox.maps.extension.style.layers.generated.FillExtrusionLayer('3d-buildings', 'composite');
2148
+ fillExtrusionLayer.sourceLayer('building');
2149
+ fillExtrusionLayer.minZoom(15);
2150
+ LayerFactory.applyLayerProperties(fillExtrusionLayer, {
2151
+ 'fill-extrusion-color': android.graphics.Color.LTGRAY,
2152
+ 'fill-extrusion-height': '["get", "height]',
2153
+ 'fill-extrusion-base': '["get", "min_height]',
2154
+ 'fill-extrusion-opacity': 0.6,
2155
+ filter: '["==", ["get", "extrude"], true]'
2156
+ });
2157
+ // TODO: missing extension typings
2158
+ //@ts-ignore
2084
2159
  this._mapboxMapInstance.getStyle().addLayer(fillExtrusionLayer);
2085
2160
  resolve();
2086
2161
  }
@@ -2104,7 +2179,7 @@ export class Mapbox extends MapboxCommon {
2104
2179
  reject('No map has been loaded');
2105
2180
  return;
2106
2181
  }
2107
- const source = theMap.getStyle().getSource(id);
2182
+ const source = this.getSource(id, theMap);
2108
2183
  if (!source) {
2109
2184
  reject('Source does not exists: ' + id);
2110
2185
  return;
@@ -2112,7 +2187,7 @@ export class Mapbox extends MapboxCommon {
2112
2187
  switch (options.type) {
2113
2188
  case 'geojson':
2114
2189
  const geoJsonString = JSON.stringify(options.data);
2115
- source.setGeoJson(geoJsonString);
2190
+ source.data(geoJsonString);
2116
2191
  resolve();
2117
2192
  break;
2118
2193
  default:
@@ -2145,33 +2220,39 @@ export class Mapbox extends MapboxCommon {
2145
2220
  reject('No map has been loaded');
2146
2221
  return;
2147
2222
  }
2148
- if (theMap.getStyle().getSource(id)) {
2223
+ if (this.getSource(id, theMap)) {
2149
2224
  reject('Source exists: ' + id);
2150
2225
  return;
2151
2226
  }
2152
2227
  switch (options.type) {
2153
2228
  case 'vector': {
2229
+ const builder = new com.mapbox.maps.extension.style.sources.generated.VectorSource.Builder(id);
2154
2230
  if (options.url) {
2155
- source = new com.mapbox.mapboxsdk.style.sources.VectorSource(id, options.url);
2231
+ builder.url(options.url);
2156
2232
  }
2157
2233
  else {
2158
- const tiles = Array.create(java.lang.String, options.tiles.length);
2159
- options.tiles.forEach((val, i) => (tiles[i] = val));
2160
- const tileSet = new com.mapbox.mapboxsdk.style.sources.TileSet('2.0.0', tiles);
2161
- if (options.minzoom) {
2162
- tileSet.setMinZoom(options.minzoom);
2163
- }
2164
- if (options.maxzoom) {
2165
- tileSet.setMaxZoom(options.maxzoom);
2166
- }
2167
- if (options.scheme) {
2168
- tileSet.setScheme(options.scheme);
2169
- }
2170
- if (options.bounds) {
2171
- tileSet.setBounds(options.bounds.map((val) => new java.lang.Float(val)));
2234
+ builder.tiles(java.util.Arrays.asList(options.tiles));
2235
+ }
2236
+ if (options.minzoom) {
2237
+ builder.minzoom(options.minzoom);
2238
+ }
2239
+ if (options.maxzoom) {
2240
+ builder.maxzoom(options.maxzoom);
2241
+ }
2242
+ if (options.scheme) {
2243
+ switch (options.scheme) {
2244
+ case 'tms':
2245
+ builder.scheme(com.mapbox.maps.extension.style.sources.generated.Scheme.TMS);
2246
+ break;
2247
+ default:
2248
+ builder.scheme(com.mapbox.maps.extension.style.sources.generated.Scheme.XYZ);
2249
+ break;
2172
2250
  }
2173
- source = new com.mapbox.mapboxsdk.style.sources.VectorSource(id, tileSet);
2174
2251
  }
2252
+ if (options.bounds) {
2253
+ builder.bounds(java.util.Arrays.asList(options.bounds.map((val) => java.lang.Float.valueOf(val))));
2254
+ }
2255
+ source = builder.build();
2175
2256
  break;
2176
2257
  }
2177
2258
  case 'geojson': {
@@ -2179,21 +2260,21 @@ export class Mapbox extends MapboxCommon {
2179
2260
  CLog(CLogTypes.info, 'Mapbox:addSource(): before addSource with geojson');
2180
2261
  CLog(CLogTypes.info, 'Mapbox:addSource(): before adding geoJSON to GeoJsonSource');
2181
2262
  }
2182
- const geojsonOptions = new com.mapbox.mapboxsdk.style.sources.GeoJsonOptions();
2183
- if (options.minzoom) {
2184
- geojsonOptions.withMinZoom(options.minzoom);
2185
- }
2263
+ let builder = new com.mapbox.maps.extension.style.sources.generated.GeoJsonSource.Builder(id);
2264
+ // if (options.minzoom) {
2265
+ // builder.minzoom(options.minzoom);
2266
+ // }
2186
2267
  if (options.maxzoom) {
2187
- geojsonOptions.withMaxZoom(options.maxzoom);
2268
+ builder.maxzoom(options.maxzoom);
2188
2269
  }
2189
2270
  if (options.lineMetrics !== undefined) {
2190
- geojsonOptions.withLineMetrics(options.lineMetrics);
2271
+ builder.lineMetrics(options.lineMetrics);
2191
2272
  }
2192
2273
  if (options.cluster) {
2193
- geojsonOptions
2194
- .withCluster(true)
2195
- .withClusterMaxZoom(options.cluster.maxZoom || 13)
2196
- .withClusterRadius(options.cluster.radius || 40);
2274
+ builder = builder
2275
+ .cluster(true)
2276
+ .clusterMaxZoom(options.cluster.maxZoom || 13)
2277
+ .clusterRadius(options.cluster.radius || 40);
2197
2278
  if (options.cluster.properties) {
2198
2279
  for (const property of Object.keys(options.cluster.properties)) {
2199
2280
  const propertyValues = options.cluster.properties[property];
@@ -2201,36 +2282,42 @@ export class Mapbox extends MapboxCommon {
2201
2282
  if (!Array.isArray(operator)) {
2202
2283
  operator = [operator];
2203
2284
  }
2204
- geojsonOptions.withClusterProperty(property, ExpressionParser.parseJson(operator), ExpressionParser.parseJson(propertyValues[1]));
2285
+ builder.clusterProperty(property, ExpressionParser.parseJson(operator), ExpressionParser.parseJson(propertyValues[1]));
2205
2286
  }
2206
2287
  }
2207
2288
  }
2208
- const geoJsonSource = new com.mapbox.mapboxsdk.style.sources.GeoJsonSource(id, geojsonOptions);
2209
2289
  if (options.data) {
2210
2290
  const geoJsonString = JSON.stringify(options.data);
2211
- geoJsonSource.setGeoJson(geoJsonString);
2291
+ builder.data(geoJsonString);
2212
2292
  }
2293
+ const geoJsonSource = builder.build();
2213
2294
  source = geoJsonSource;
2214
2295
  break;
2215
2296
  }
2216
2297
  case 'raster':
2217
- // use Array.create because a marshal error throws on TileSet if options.tiles directly passed.
2218
- const tiles = Array.create(java.lang.String, options.tiles.length);
2219
- options.tiles.forEach((val, i) => (tiles[i] = val));
2220
- const tileSet = new com.mapbox.mapboxsdk.style.sources.TileSet('2.0.0', tiles);
2298
+ const builder = new com.mapbox.maps.extension.style.sources.generated.RasterSource.Builder(id);
2299
+ builder.tiles(java.util.Arrays.asList(options.tiles));
2221
2300
  if (options.minzoom) {
2222
- tileSet.setMinZoom(options.minzoom);
2301
+ builder.minzoom(options.minzoom);
2223
2302
  }
2224
2303
  if (options.maxzoom) {
2225
- tileSet.setMaxZoom(options.maxzoom);
2304
+ builder.maxzoom(options.maxzoom);
2226
2305
  }
2227
2306
  if (options.scheme) {
2228
- tileSet.setScheme(options.scheme);
2307
+ switch (options.scheme) {
2308
+ case 'tms':
2309
+ builder.scheme(com.mapbox.maps.extension.style.sources.generated.Scheme.TMS);
2310
+ break;
2311
+ default:
2312
+ builder.scheme(com.mapbox.maps.extension.style.sources.generated.Scheme.XYZ);
2313
+ break;
2314
+ }
2229
2315
  }
2230
2316
  if (options.bounds) {
2231
- tileSet.setBounds(options.bounds.map((val) => new java.lang.Float(val)));
2317
+ builder.bounds(java.util.Arrays.asList(options.bounds.map((val) => java.lang.Float.valueOf(val))));
2232
2318
  }
2233
- source = new com.mapbox.mapboxsdk.style.sources.RasterSource(id, tileSet, options.tileSize || 256);
2319
+ builder.tileSize(options.tileSize || 256);
2320
+ source = builder.build();
2234
2321
  break;
2235
2322
  default:
2236
2323
  reject('Invalid source type: ' + options['type']);
@@ -2244,6 +2331,8 @@ export class Mapbox extends MapboxCommon {
2244
2331
  reject(ex);
2245
2332
  return;
2246
2333
  }
2334
+ // TODO: missing extension typings
2335
+ //@ts-ignore
2247
2336
  theMap.getStyle().addSource(source);
2248
2337
  resolve();
2249
2338
  }
@@ -2294,7 +2383,7 @@ export class Mapbox extends MapboxCommon {
2294
2383
  * - only a subset of paint properties are available.
2295
2384
  *
2296
2385
  * @param {object} style - a style following the Mapbox style specification.
2297
- * @param {any} nativeMapView - native map view (com.mapbox.mapboxsdk.maps.MapView)
2386
+ * @param {any} nativeMapView - native map view (com.mapbox.maps.MapView)
2298
2387
  *
2299
2388
  * @link https://docs.mapbox.com/mapbox-gl-js/style-spec/#layers
2300
2389
  */
@@ -2304,19 +2393,24 @@ export class Mapbox extends MapboxCommon {
2304
2393
  return Promise.reject('No map has been loaded');
2305
2394
  }
2306
2395
  let source = null;
2307
- if (typeof style.source != 'string') {
2396
+ if (typeof style.source !== 'string') {
2308
2397
  await this.addSource(style.id + '_source', style.source);
2309
- source = theMap.getStyle().getSource(style.id + '_source');
2398
+ source = this.getSource(style.id + '_source', theMap);
2310
2399
  }
2311
2400
  else {
2312
- source = theMap.getStyle().getSource(style.source);
2401
+ source = this.getSource(style.source, theMap);
2313
2402
  }
2314
2403
  const layer = await LayerFactory.createLayer(style, source);
2315
2404
  if (belowLayerId) {
2405
+ // TODO: missing extension typings
2406
+ //@ts-ignore
2316
2407
  this._mapboxMapInstance.getStyle().addLayerBelow(layer.getNativeInstance(), belowLayerId);
2317
- return;
2318
2408
  }
2319
- this._mapboxMapInstance.getStyle().addLayer(layer.getNativeInstance());
2409
+ else {
2410
+ // TODO: missing extension typings
2411
+ //@ts-ignore
2412
+ this._mapboxMapInstance.getStyle().addLayer(layer.getNativeInstance());
2413
+ }
2320
2414
  }
2321
2415
  /**
2322
2416
  * remove layer by ID
@@ -2332,6 +2426,11 @@ export class Mapbox extends MapboxCommon {
2332
2426
  CLog(CLogTypes.info, 'Mapbox:removeLayer(): after removing layer');
2333
2427
  }
2334
2428
  }
2429
+ getSource(sId, mapboxInstance = this._mapboxMapInstance) {
2430
+ // TODO: missing extension typings
2431
+ //@ts-ignore
2432
+ return mapboxInstance.getStyle().getSource(sId);
2433
+ }
2335
2434
  /**
2336
2435
  * @deprecated
2337
2436
  * Add a point to a line
@@ -2346,33 +2445,52 @@ export class Mapbox extends MapboxCommon {
2346
2445
  * @link https://docs.oracle.com/javase/8/docs/api/java/util/List.html
2347
2446
  */
2348
2447
  async addLinePoint(id, lnglat, sourceId, nativeMapView) {
2349
- try {
2350
- const sId = !!sourceId ? sourceId : id + '_source';
2351
- const lineSource = this._mapboxMapInstance.getStyle().getSource(sId);
2352
- if (!lineSource) {
2353
- throw new Error(`no source found with id: ${sId}`);
2448
+ return new Promise((resolve, reject) => {
2449
+ try {
2450
+ const sId = !!sourceId ? sourceId : id + '_source';
2451
+ const lineSource = this.getSource(sId);
2452
+ if (!lineSource) {
2453
+ throw new Error(`no source found with id: ${sId}`);
2454
+ }
2455
+ this._mapboxMapInstance.querySourceFeatures(sId, new com.mapbox.maps.SourceQueryOptions(null, // source layer IDs
2456
+ ExpressionParser.parseJson(['==', '$type', 'LineString'])), new com.mapbox.maps.QuerySourceFeaturesCallback({
2457
+ run(result) {
2458
+ if (result.isError()) {
2459
+ reject(new Error(result.getError()));
2460
+ }
2461
+ else {
2462
+ const lineFeatures = result.getValue();
2463
+ if (lineFeatures.size() === 0) {
2464
+ reject(new Error('no line string feature found'));
2465
+ }
2466
+ else {
2467
+ const feature = lineFeatures.get(0).getQueriedFeature().getFeature();
2468
+ const newPoints = new java.util.ArrayList(feature.geometry().coordinates());
2469
+ newPoints.add(com.mapbox.geojson.Point.fromLngLat(lnglat[0], lnglat[1]));
2470
+ const newFeature = com.mapbox.geojson.LineString.fromLngLats(newPoints);
2471
+ lineSource.geometry(newFeature);
2472
+ }
2473
+ }
2474
+ }
2475
+ }));
2354
2476
  }
2355
- const lineFeatures = lineSource.querySourceFeatures(ExpressionParser.parseJson(['==', '$type', 'LineString']));
2356
- if (lineFeatures.size() === 0) {
2357
- throw new Error('no line string feature found');
2477
+ catch (error) {
2478
+ reject(error);
2358
2479
  }
2359
- const feature = lineFeatures.get(0);
2360
- const newPoints = new java.util.ArrayList(feature.geometry().coordinates());
2361
- newPoints.add(com.mapbox.geojson.Point.fromLngLat(lnglat[0], lnglat[1]));
2362
- const newFeature = com.mapbox.geojson.LineString.fromLngLats(newPoints);
2363
- lineSource.setGeoJson(newFeature);
2364
- }
2365
- catch (error) {
2366
- return error;
2367
- }
2480
+ });
2368
2481
  }
2369
2482
  addGeoJsonClustered(options, nativeMap) {
2370
2483
  return new Promise((resolve, reject) => {
2371
2484
  try {
2372
- this._mapboxMapInstance.getStyle().addSource(new com.mapbox.mapboxsdk.style.sources.GeoJsonSource(options.name, new java.net.URL(options.data), new com.mapbox.mapboxsdk.style.sources.GeoJsonOptions()
2373
- .withCluster(true)
2374
- .withClusterMaxZoom(options.clusterMaxZoom || 13)
2375
- .withClusterRadius(options.clusterRadius || 40)));
2485
+ const geoJsonSource = new com.mapbox.maps.extension.style.sources.generated.GeoJsonSource.Builder(options.name)
2486
+ .data(options.data)
2487
+ .cluster(true) // enable clustering
2488
+ .clusterMaxZoom(options.clusterMaxZoom || 13) // maximum zoom to cluster points
2489
+ .clusterRadius(options.clusterRadius || 40) // radius of each cluster in pixels
2490
+ .build();
2491
+ // TODO: missing extension typings
2492
+ //@ts-ignore
2493
+ this._mapboxMapInstance.getStyle().addSource(geoJsonSource);
2376
2494
  const layers = [];
2377
2495
  if (options.clusters) {
2378
2496
  for (let i = 0; i < options.clusters.length; i++) {
@@ -2385,42 +2503,58 @@ export class Mapbox extends MapboxCommon {
2385
2503
  layers.push([20, new Color('green').android]);
2386
2504
  layers.push([0, new Color('blue').android]);
2387
2505
  }
2388
- const unclustered = new com.mapbox.mapboxsdk.style.layers.SymbolLayer('unclustered-points', options.name);
2389
- unclustered.setProperties([
2390
- com.mapbox.mapboxsdk.style.layers.PropertyFactory.circleColor(new Color('red').android),
2391
- com.mapbox.mapboxsdk.style.layers.PropertyFactory.circleRadius(new java.lang.Float(16.0)),
2392
- com.mapbox.mapboxsdk.style.layers.PropertyFactory.circleBlur(new java.lang.Float(0.2))
2393
- ]);
2394
- unclustered.setFilter(com.mapbox.mapboxsdk.style.expressions.Expression.neq(com.mapbox.mapboxsdk.style.expressions.Expression.get('cluster'), true));
2506
+ const unclustered = new com.mapbox.maps.extension.style.layers.generated.SymbolLayer('unclustered-points', options.name);
2507
+ LayerFactory.applyLayerProperties(unclustered, {
2508
+ 'circle-color': 'red',
2509
+ 'circle-radius': 16,
2510
+ 'circle-blur': 0.2,
2511
+ filter: `["!=", ["get", "cluster"], true]`
2512
+ });
2513
+ // unclustered.setFilter(com.mapbox.maps.style.expressions.Expression.neq(com.mapbox.maps.style.expressions.Expression.get('cluster'), true));
2514
+ // TODO: missing extension typings
2515
+ //@ts-ignore
2395
2516
  this._mapboxMapInstance.getStyle().addLayer(unclustered); // , "building");
2396
2517
  for (let i = 0; i < layers.length; i++) {
2397
2518
  // Add some nice circles
2398
- const circles = new com.mapbox.mapboxsdk.style.layers.CircleLayer('cluster-' + i, options.name);
2399
- circles.setProperties([
2400
- // com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconImage("icon")
2401
- com.mapbox.mapboxsdk.style.layers.PropertyFactory.circleColor(layers[i][1]),
2402
- com.mapbox.mapboxsdk.style.layers.PropertyFactory.circleRadius(new java.lang.Float(22.0)),
2403
- com.mapbox.mapboxsdk.style.layers.PropertyFactory.circleBlur(new java.lang.Float(0.2))
2404
- ]);
2405
- const pointCount = com.mapbox.mapboxsdk.style.expressions.Expression.toNumber(com.mapbox.mapboxsdk.style.expressions.Expression.get('point_count'));
2519
+ const circles = new com.mapbox.maps.extension.style.layers.generated.CircleLayer('cluster-' + i, options.name);
2520
+ const properties = {
2521
+ 'circle-color': layers[i][1],
2522
+ 'circle-radius': 22,
2523
+ 'circle-blur': 0.2
2524
+ };
2406
2525
  if (i === 0) {
2407
- circles.setFilter(com.mapbox.mapboxsdk.style.expressions.Expression.gte(pointCount, com.mapbox.mapboxsdk.style.expressions.Expression.literal(java.lang.Integer.valueOf(layers[i][0]))));
2526
+ properties['filter'] = `[">=", ["get", "point_count"], ${layers[i][0]}]`;
2527
+ // circles.setFilter(com.mapbox.maps.style.expressions.Expression.gte(pointCount, com.mapbox.maps.style.expressions.Expression.literal(java.lang.Integer.valueOf(layers[i][0]))));
2408
2528
  }
2409
2529
  else {
2410
- circles.setFilter(com.mapbox.mapboxsdk.style.expressions.Expression.all([
2411
- com.mapbox.mapboxsdk.style.expressions.Expression.gte(pointCount, com.mapbox.mapboxsdk.style.expressions.Expression.literal(java.lang.Integer.valueOf(layers[i][0]))),
2412
- com.mapbox.mapboxsdk.style.expressions.Expression.lt(pointCount, com.mapbox.mapboxsdk.style.expressions.Expression.literal(java.lang.Integer.valueOf(layers[i - 1][0])))
2413
- ]));
2530
+ properties['filter'] = `["all", [">=", ["get", "point_count"], ${layers[i][0]}], ["<", ["get", "point_count"], ${layers[i - 1][0]}]]`;
2531
+ // (
2532
+ // com.mapbox.maps.style.expressions.Expression.all([
2533
+ // com.mapbox.maps.style.expressions.Expression.gte(pointCount, com.mapbox.maps.style.expressions.Expression.literal(java.lang.Integer.valueOf(layers[i][0]))),
2534
+ // com.mapbox.maps.style.expressions.Expression.lt(pointCount, com.mapbox.maps.style.expressions.Expression.literal(java.lang.Integer.valueOf(layers[i - 1][0])))
2535
+ // ])
2536
+ // );
2414
2537
  }
2538
+ LayerFactory.applyLayerProperties(circles, properties);
2539
+ // const pointCount = com.mapbox.maps.style.expressions.Expression.toNumber(com.mapbox.maps.style.expressions.Expression.get('point_count'));
2540
+ // TODO: missing extension typings
2541
+ //@ts-ignore
2415
2542
  this._mapboxMapInstance.getStyle().addLayer(circles); // , "building");
2416
2543
  }
2417
2544
  // Add the count labels (note that this doesn't show.. #sad)
2418
- const count = new com.mapbox.mapboxsdk.style.layers.SymbolLayer('count', options.name);
2419
- count.setProperties([
2420
- com.mapbox.mapboxsdk.style.layers.PropertyFactory.textField(com.mapbox.mapboxsdk.style.expressions.Expression.get('point_count')),
2421
- com.mapbox.mapboxsdk.style.layers.PropertyFactory.textSize(new java.lang.Float(12.0)),
2422
- com.mapbox.mapboxsdk.style.layers.PropertyFactory.textColor(new Color('white').android)
2423
- ]);
2545
+ const count = new com.mapbox.maps.extension.style.layers.generated.SymbolLayer('count', options.name);
2546
+ LayerFactory.applyLayerProperties(count, {
2547
+ 'text-field': '["get", "point_count"]',
2548
+ 'text-size': 12,
2549
+ 'text-color': 'white'
2550
+ });
2551
+ // count.setProperties([
2552
+ // com.mapbox.maps.extension.style.layers.generated.PropertyFactory.textField(com.mapbox.maps.style.expressions.Expression.get('point_count')),
2553
+ // com.mapbox.maps.extension.style.layers.generated.PropertyFactory.textSize(new java.lang.Float(12.0)),
2554
+ // com.mapbox.maps.extension.style.layers.generated.PropertyFactory.textColor(new Color('white').android)
2555
+ // ]);
2556
+ // TODO: missing extension typings
2557
+ //@ts-ignore
2424
2558
  this._mapboxMapInstance.getStyle().addLayer(count);
2425
2559
  resolve();
2426
2560
  }
@@ -2447,14 +2581,11 @@ export class Mapbox extends MapboxCommon {
2447
2581
  }
2448
2582
  this.requestFineLocationPermission()
2449
2583
  .then(() => {
2450
- if (this._locationComponent) {
2451
- this.changeUserLocationMarkerMode(options.renderMode || 'COMPASS', options.cameraMode || 'TRACKING');
2452
- }
2453
- else {
2454
- this.showUserLocationMarker({
2455
- useDefaultLocationEngine: true
2456
- });
2457
- }
2584
+ // if (this._locationComponent) {
2585
+ // this.changeUserLocationMarkerMode(options.renderMode || 'COMPASS', options.cameraMode || 'TRACKING');
2586
+ // } else {
2587
+ this.showUserLocationMarker(options);
2588
+ // }
2458
2589
  })
2459
2590
  .catch((err) => {
2460
2591
  console.error('Location permission denied. error:', err);
@@ -2470,20 +2601,19 @@ export class Mapbox extends MapboxCommon {
2470
2601
  });
2471
2602
  }
2472
2603
  static getAndroidColor(color) {
2473
- let androidColor;
2474
- if (color && Color.isValid(color)) {
2475
- androidColor = new Color('' + color).android;
2604
+ const temp = color instanceof Color ? color : new Color(color);
2605
+ if (Color.isValid(temp)) {
2606
+ return temp.android;
2476
2607
  }
2477
2608
  else {
2478
- androidColor = new Color('#000').android;
2609
+ return android.graphics.Color.BLACK;
2479
2610
  }
2480
- return androidColor;
2481
2611
  }
2482
2612
  _getMapStyle(input) {
2483
2613
  if (Trace.isEnabled()) {
2484
2614
  CLog(CLogTypes.info, '_getMapStyle(): top with input:', input);
2485
2615
  }
2486
- const Style = com.mapbox.mapboxsdk.maps.Style;
2616
+ const Style = com.mapbox.maps.Style;
2487
2617
  // allow for a style URL to be passed
2488
2618
  if (input.startsWith('mapbox://styles') || input.startsWith('http://') || input.startsWith('https://')) {
2489
2619
  return input;
@@ -2491,30 +2621,12 @@ export class Mapbox extends MapboxCommon {
2491
2621
  else if (input.startsWith('~/')) {
2492
2622
  return 'file://' + path.join(knownFolders.currentApp().path, input.replace('~/', ''));
2493
2623
  }
2494
- else if (input === MapStyle.LIGHT) {
2495
- return Style.LIGHT;
2496
- }
2497
- else if (input === MapStyle.DARK) {
2498
- return Style.DARK;
2499
- }
2500
- else if (input === MapStyle.OUTDOORS) {
2501
- return Style.OUTDOORS;
2502
- }
2503
- else if (input === MapStyle.SATELLITE) {
2504
- return Style.SATELLITE;
2505
- }
2506
- else if (input === MapStyle.SATELLITE_STREETS) {
2507
- return Style.SATELLITE_STREETS;
2508
- }
2509
- else if (input === MapStyle.TRAFFIC_DAY) {
2510
- return Style.TRAFFIC_DAY;
2511
- }
2512
- else if (input === MapStyle.TRAFFIC_NIGHT) {
2513
- return Style.TRAFFIC_NIGHT;
2514
- }
2515
2624
  else {
2516
- // default
2517
- return Style.MAPBOX_STREETS;
2625
+ const key = Object.keys(MapStyle)[Object.values(MapStyle).indexOf(input)];
2626
+ // fix because MAPBOX_STREETS and others are not exposed by the
2627
+ const field = Style.class.getDeclaredField(key) || Style.class.getDeclaredField('MAPBOX_STREETS');
2628
+ field.setAccessible(true);
2629
+ return field.get(null);
2518
2630
  }
2519
2631
  }
2520
2632
  /**
@@ -2524,18 +2636,8 @@ export class Mapbox extends MapboxCommon {
2524
2636
  * @link https://github.com/mapbox/mapbox-gl-native/blob/master/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/MapboxMapOptions.java
2525
2637
  * @link https://docs.mapbox.com/android/api/map-sdk/7.1.2/com/mapbox/mapboxsdk/maps/MapboxMapOptions.html
2526
2638
  */
2527
- _getMapboxMapOptions(settings) {
2528
- const mapboxMapOptions = new com.mapbox.mapboxsdk.maps.MapboxMapOptions()
2529
- .compassEnabled(!settings.hideCompass)
2530
- .compassGravity(Mapbox.mapPositionToGravity(settings.compassPosition))
2531
- .rotateGesturesEnabled(!settings.disableRotation)
2532
- .scrollGesturesEnabled(!settings.disableScroll)
2533
- .tiltGesturesEnabled(!settings.disableTilt)
2534
- .zoomGesturesEnabled(!settings.disableZoom)
2535
- .attributionEnabled(!settings.hideAttribution)
2536
- .attributionGravity(Mapbox.mapPositionToGravity(settings.attributionPosition))
2537
- .logoEnabled(!settings.hideLogo)
2538
- .logoGravity(Mapbox.mapPositionToGravity(settings.logoPosition));
2639
+ _getMapboxMapOptions(context, settings) {
2640
+ const mapOptions = new com.mapbox.maps.MapOptions.Builder().pixelRatio(context.getResources().getDisplayMetrics().density).build();
2539
2641
  // zoomlevel is not applied unless center is set
2540
2642
  if (settings.zoomLevel && !settings.center) {
2541
2643
  // Eiffel tower, Paris
@@ -2544,13 +2646,15 @@ export class Mapbox extends MapboxCommon {
2544
2646
  lng: 2.294694
2545
2647
  };
2546
2648
  }
2649
+ let initialCameraOptions;
2547
2650
  if (settings.center && settings.center.lat && settings.center.lng) {
2548
- const cameraPositionBuilder = new com.mapbox.mapboxsdk.camera.CameraPosition.Builder()
2549
- .zoom(settings.zoomLevel)
2550
- .target(new com.mapbox.mapboxsdk.geometry.LatLng(settings.center.lat, settings.center.lng));
2551
- mapboxMapOptions.camera(cameraPositionBuilder.build());
2651
+ initialCameraOptions = new com.mapbox.maps.CameraOptions.Builder()
2652
+ .zoom(java.lang.Double.valueOf(settings.zoomLevel))
2653
+ .center(com.mapbox.geojson.Point.fromLngLat(settings.center.lng, settings.center.lat))
2654
+ .build();
2552
2655
  }
2553
- return mapboxMapOptions;
2656
+ com.mapbox.common.MapboxOptions.setAccessToken(this._accessToken);
2657
+ return new com.mapbox.maps.MapInitOptions(context, mapOptions, com.mapbox.maps.MapInitOptions.Companion.getDefaultPluginList(), initialCameraOptions, false);
2554
2658
  }
2555
2659
  static mapPositionToGravity(position) {
2556
2660
  switch (position) {
@@ -2569,86 +2673,102 @@ export class Mapbox extends MapboxCommon {
2569
2673
  *
2570
2674
  * @link https://docs.mapbox.com/android/api/map-sdk/8.1.0/com/mapbox/mapboxsdk/location/modes/CameraMode.html
2571
2675
  */
2572
- _stringToCameraMode(mode) {
2573
- const modeRef = com.mapbox.mapboxsdk.location.modes.CameraMode;
2574
- switch (mode) {
2575
- case 'NONE':
2576
- return modeRef.NONE;
2577
- case 'NONE_COMPASS':
2578
- return modeRef.NONE_COMPASS;
2579
- case 'NONE_GPS':
2580
- return modeRef.NONE_GPS;
2581
- case 'TRACKING':
2582
- return modeRef.TRACKING;
2583
- case 'TRACKING_COMPASS':
2584
- return modeRef.TRACKING_COMPASS;
2585
- case 'TRACKING_GPS':
2586
- return modeRef.TRACKING_GPS;
2587
- case 'TRACKING_GPS_NORTH':
2588
- return modeRef.TRACKING_GPS_NORTH;
2589
- }
2590
- }
2591
- /**
2592
- * convert string to render mode
2593
- */
2594
- _stringToRenderMode(mode) {
2595
- let renderMode;
2596
- switch (mode) {
2597
- case 'NORMAL':
2598
- renderMode = com.mapbox.mapboxsdk.location.modes.RenderMode.NORMAL;
2599
- break;
2600
- case 'COMPASS':
2601
- renderMode = com.mapbox.mapboxsdk.location.modes.RenderMode.COMPASS;
2602
- break;
2603
- case 'GPS':
2604
- renderMode = com.mapbox.mapboxsdk.location.modes.RenderMode.GPS;
2605
- break;
2606
- }
2607
- return renderMode;
2608
- }
2609
- _convertCameraMode(mode) {
2610
- const modeRef = com.mapbox.mapboxsdk.location.modes.CameraMode;
2611
- switch (mode) {
2612
- case modeRef.NONE:
2613
- return 'NONE';
2614
- case modeRef.NONE_COMPASS:
2615
- return 'NONE_COMPASS';
2616
- case modeRef.NONE_GPS:
2617
- return 'NONE_GPS';
2618
- case modeRef.TRACKING:
2619
- return 'TRACKING';
2620
- case modeRef.TRACKING_COMPASS:
2621
- return 'TRACKING_COMPASS';
2622
- case modeRef.TRACKING_GPS:
2623
- return 'TRACKING_GPS';
2624
- case modeRef.TRACKING_GPS_NORTH:
2625
- return 'TRACKING_GPS_NORTH';
2626
- }
2627
- return 'NONE';
2628
- }
2676
+ // _stringToCameraMode(mode: UserLocationCameraMode): any {
2677
+ // const modeRef = com.mapbox.maps.location.modes.CameraMode;
2678
+ // switch (mode) {
2679
+ // case 'NONE':
2680
+ // return modeRef.NONE;
2681
+ // case 'NONE_COMPASS':
2682
+ // return modeRef.NONE_COMPASS;
2683
+ // case 'NONE_GPS':
2684
+ // return modeRef.NONE_GPS;
2685
+ // case 'TRACKING':
2686
+ // return modeRef.TRACKING;
2687
+ // case 'TRACKING_COMPASS':
2688
+ // return modeRef.TRACKING_COMPASS;
2689
+ // case 'TRACKING_GPS':
2690
+ // return modeRef.TRACKING_GPS;
2691
+ // case 'TRACKING_GPS_NORTH':
2692
+ // return modeRef.TRACKING_GPS_NORTH;
2693
+ // }
2694
+ // }
2695
+ // /**
2696
+ // * convert string to render mode
2697
+ // */
2698
+ // _stringToRenderMode(mode): any {
2699
+ // let renderMode: any;
2700
+ // switch (mode) {
2701
+ // case 'NORMAL':
2702
+ // renderMode = com.mapbox.maps.location.modes.RenderMode.NORMAL;
2703
+ // break;
2704
+ // case 'COMPASS':
2705
+ // renderMode = com.mapbox.maps.location.modes.RenderMode.COMPASS;
2706
+ // break;
2707
+ // case 'GPS':
2708
+ // renderMode = com.mapbox.maps.location.modes.RenderMode.GPS;
2709
+ // break;
2710
+ // }
2711
+ // return renderMode;
2712
+ // }
2713
+ // _convertCameraMode(mode: any): UserLocationCameraMode {
2714
+ // const modeRef = com.mapbox.maps.plugin.locationcomponent.camera.CameraMode;
2715
+ // switch (mode) {
2716
+ // case modeRef.NONE:
2717
+ // return 'NONE';
2718
+ // case modeRef.NONE_COMPASS:
2719
+ // return 'NONE_COMPASS';
2720
+ // case modeRef.NONE_GPS:
2721
+ // return 'NONE_GPS';
2722
+ // case modeRef.TRACKING:
2723
+ // return 'TRACKING';
2724
+ // case modeRef.TRACKING_COMPASS:
2725
+ // return 'TRACKING_COMPASS';
2726
+ // case modeRef.TRACKING_GPS:
2727
+ // return 'TRACKING_GPS';
2728
+ // case modeRef.TRACKING_GPS_NORTH:
2729
+ // return 'TRACKING_GPS_NORTH';
2730
+ // }
2731
+ // return 'NONE';
2732
+ // }
2629
2733
  _fineLocationPermissionGranted() {
2630
2734
  let hasPermission = android.os.Build.VERSION.SDK_INT < 23; // Android M. (6.0)
2631
2735
  if (!hasPermission) {
2632
- hasPermission = com.mapbox.android.core.permissions.PermissionsManager.areLocationPermissionsGranted(Application.android.context);
2736
+ hasPermission = com.mapbox.android.core.permissions.PermissionsManager.areLocationPermissionsGranted(Utils.android.getApplicationContext());
2633
2737
  }
2634
2738
  return hasPermission;
2635
2739
  }
2636
- _getRegionName(offlineRegion) {
2637
- const metadata = offlineRegion.getMetadata();
2638
- const jsonStr = new java.lang.String(metadata, 'UTF-8');
2639
- const jsonObj = new org.json.JSONObject(jsonStr);
2640
- try {
2641
- return jsonObj.getString('name');
2642
- }
2643
- catch (error) {
2644
- return '';
2645
- }
2740
+ async _getRegionName(offlineRegion) {
2741
+ return (await this._getRegionMetadata(offlineRegion))?.name;
2646
2742
  }
2647
2743
  _getRegionMetadata(offlineRegion) {
2648
- const metadata = offlineRegion.getMetadata();
2649
- const jsonStr = new java.lang.String(metadata, 'UTF-8');
2650
- const jsonObj = new org.json.JSONObject(jsonStr);
2651
- return JSON.parse(jsonObj.toString());
2744
+ return new Promise((resolve, reject) => {
2745
+ this._getTileStore().getTileRegionMetadata(offlineRegion.getId(), new com.mapbox.common.TileRegionMetadataCallback({
2746
+ run(result) {
2747
+ if (result.isError()) {
2748
+ reject(result.getError());
2749
+ }
2750
+ else {
2751
+ try {
2752
+ resolve(JSON.parse(result.getValue().toString() || '{}') || {});
2753
+ }
2754
+ catch (error) {
2755
+ resolve(JSON.parse(result.getValue().toJson() || '{}') || {});
2756
+ }
2757
+ }
2758
+ }
2759
+ }));
2760
+ });
2761
+ }
2762
+ _getPlugin(pluginId) {
2763
+ if (this._plugins[pluginId]) {
2764
+ return this._plugins[pluginId];
2765
+ }
2766
+ const plugin = (this._plugins[pluginId] = this._mapboxViewInstance.getPlugin(pluginId));
2767
+ return plugin;
2768
+ }
2769
+ _getGesturesPlugin() {
2770
+ return this._getPlugin('MAPBOX_GESTURES_PLUGIN_ID');
2771
+ // return this._mapboxMapInstance.getGestures() as com.mapbox.maps.plugin.gestures.GesturesPlugin;
2652
2772
  }
2653
2773
  /**
2654
2774
  * show a user location marker
@@ -2677,94 +2797,120 @@ export class Mapbox extends MapboxCommon {
2677
2797
  *
2678
2798
  * @todo at least with simulated data, the location is only updated once hence adding support for forceLocation method.
2679
2799
  */
2680
- showUserLocationMarker(options, nativeMap) {
2681
- return new Promise((resolve, reject) => {
2682
- try {
2683
- if (Trace.isEnabled()) {
2684
- CLog(CLogTypes.info, 'showUserLocationMarker()');
2685
- }
2686
- if (!this._mapboxMapInstance) {
2687
- reject('No map has been loaded');
2688
- return;
2689
- }
2690
- if (!com.mapbox.android.core.permissions.PermissionsManager.areLocationPermissionsGranted(Application.android.context)) {
2691
- if (Trace.isEnabled()) {
2692
- CLog(CLogTypes.info, 'showUserLocationMarker(): location permissions are not granted.');
2693
- }
2694
- reject('Location permissions not granted.');
2695
- return;
2696
- }
2697
- let componentOptionsBuilder = com.mapbox.mapboxsdk.location.LocationComponentOptions.builder(Application.android.context);
2698
- if (typeof options.elevation != 'undefined') {
2699
- componentOptionsBuilder = componentOptionsBuilder.elevation(options.elevation);
2700
- }
2701
- if (typeof options.accuracyColor != 'undefined') {
2702
- componentOptionsBuilder = componentOptionsBuilder.accuracyColor(android.graphics.Color.parseColor(options.accuracyColor));
2703
- }
2704
- if (typeof options.accuracyAlpha != 'undefined') {
2705
- componentOptionsBuilder = componentOptionsBuilder.accuracyAlpha(options.accuracyAlpha);
2706
- }
2707
- if (typeof options.foregroundTintColor != 'undefined') {
2708
- const foregroundTintColor = new java.lang.Integer(android.graphics.Color.parseColor(options.foregroundTintColor));
2709
- componentOptionsBuilder = componentOptionsBuilder.foregroundTintColor(foregroundTintColor);
2710
- }
2711
- if (typeof options.foregroundStaleTintColor != 'undefined') {
2712
- const foregroundStaleTintColor = new java.lang.Integer(android.graphics.Color.parseColor(options.foregroundStaleTintColor));
2713
- componentOptionsBuilder = componentOptionsBuilder.foregroundStaleTintColor(foregroundStaleTintColor);
2714
- }
2715
- if (typeof options.backgroundTintColor != 'undefined') {
2716
- const backgroundTintColor = new java.lang.Integer(android.graphics.Color.parseColor(options.backgroundTintColor));
2717
- componentOptionsBuilder = componentOptionsBuilder.backgroundTintColor(backgroundTintColor);
2718
- }
2719
- if (typeof options.bearingTintColor != 'undefined') {
2720
- const bearingTintColor = new java.lang.Integer(android.graphics.Color.parseColor(options.bearingTintColor));
2721
- componentOptionsBuilder = componentOptionsBuilder.bearingTintColor(bearingTintColor);
2722
- }
2723
- const componentOptions = componentOptionsBuilder.build();
2724
- this._locationComponent = this._mapboxMapInstance.getLocationComponent();
2725
- const activationOptionsBuilder = com.mapbox.mapboxsdk.location.LocationComponentActivationOptions.builder(Application.android.context, this._mapboxMapInstance.getStyle());
2726
- activationOptionsBuilder.locationComponentOptions(componentOptions);
2727
- let useDefaultEngine = true;
2728
- if (typeof options.useDefaultLocationEngine != 'undefined') {
2729
- useDefaultEngine = options.useDefaultLocationEngine;
2730
- }
2731
- activationOptionsBuilder.useDefaultLocationEngine(useDefaultEngine);
2732
- const locationComponentActivationOptions = activationOptionsBuilder.build();
2733
- this._locationComponent.activateLocationComponent(locationComponentActivationOptions);
2734
- this._locationComponent.setLocationComponentEnabled(true);
2735
- let cameraMode = this._stringToCameraMode('TRACKING');
2736
- if (typeof options.cameraMode != 'undefined') {
2737
- cameraMode = this._stringToCameraMode(options.cameraMode);
2738
- }
2739
- this._locationComponent.setCameraMode(cameraMode);
2740
- let renderMode = com.mapbox.mapboxsdk.location.modes.RenderMode.COMPASS;
2741
- if (typeof options.renderMode != 'undefined') {
2742
- renderMode = this._stringToRenderMode(options.renderMode);
2743
- }
2744
- this._locationComponent.setRenderMode(renderMode);
2800
+ async showUserLocationMarker(options, nativeMap) {
2801
+ try {
2802
+ if (Trace.isEnabled()) {
2803
+ CLog(CLogTypes.info, 'showUserLocationMarker()');
2804
+ }
2805
+ if (!this._mapboxMapInstance) {
2806
+ throw new Error('No map has been loaded');
2807
+ }
2808
+ if (!com.mapbox.android.core.permissions.PermissionsManager.areLocationPermissionsGranted(Utils.android.getApplicationContext())) {
2745
2809
  if (Trace.isEnabled()) {
2746
- CLog(CLogTypes.info, 'showUserLocationMarker(): after renderMode');
2747
- }
2748
- if (typeof options.clickListener != 'undefined') {
2749
- this.onLocationClickListener = new com.mapbox.mapboxsdk.location.OnLocationClickListener({
2750
- onLocationComponentClick: () => {
2751
- options.clickListener();
2752
- }
2753
- });
2754
- this._locationComponent.addOnLocationClickListener(this.onLocationClickListener);
2810
+ CLog(CLogTypes.info, 'showUserLocationMarker(): location permissions are not granted.');
2755
2811
  }
2756
- if (typeof options.cameraTrackingChangedListener != 'undefined') {
2757
- this._locationComponent.addOnCameraTrackingChangedListener(options.cameraTrackingChangedListener);
2758
- }
2759
- resolve();
2812
+ throw new Error('Location permissions not granted.');
2760
2813
  }
2761
- catch (ex) {
2762
- if (Trace.isEnabled()) {
2763
- CLog(CLogTypes.info, 'Error in mapbox.showUserLocationMarker: ' + ex);
2814
+ const locationPlugin = this._getPlugin('MAPBOX_LOCATION_COMPONENT_PLUGIN_ID');
2815
+ if (this.onIndicatorPositionChangedListener) {
2816
+ locationPlugin.removeOnIndicatorPositionChangedListener(this.onIndicatorPositionChangedListener);
2817
+ }
2818
+ this.onIndicatorPositionChangedListener = new com.mapbox.maps.plugin.locationcomponent.OnIndicatorPositionChangedListener({
2819
+ onIndicatorPositionChanged: (point) => {
2820
+ this.lastKnownLocation = point;
2821
+ if (!options.cameraMode || options.cameraMode?.indexOf('TRACKING') !== -1) {
2822
+ this._mapboxMapInstance.setCamera(new com.mapbox.maps.CameraOptions.Builder().center(point).build());
2823
+ }
2764
2824
  }
2765
- reject(ex);
2825
+ });
2826
+ locationPlugin.addOnIndicatorPositionChangedListener(this.onIndicatorPositionChangedListener);
2827
+ locationPlugin.updateSettings(
2828
+ //@ts-ignore
2829
+ new kotlin.jvm.functions.Function1({
2830
+ invoke: (settings) => {
2831
+ settings.setEnabled(true);
2832
+ settings.setPulsingEnabled(true);
2833
+ console.log('setPuckBearingEnabled', options.cameraMode, options.renderMode, options.renderMode !== 'NORMAL', com.mapbox.maps.plugin.PuckBearing.HEADING, com.mapbox.maps.plugin.PuckBearing.COURSE);
2834
+ settings.setLocationPuck(com.mapbox.maps.plugin.locationcomponent.LocationComponentUtils.createDefault2DPuck(true));
2835
+ settings.setPuckBearingEnabled(options.renderMode !== 'NORMAL');
2836
+ settings.setPuckBearing(options.cameraMode?.indexOf('COMPASS') !== -1 ? com.mapbox.maps.plugin.PuckBearing.HEADING : com.mapbox.maps.plugin.PuckBearing.COURSE);
2837
+ if (options.accuracyColor !== undefined) {
2838
+ settings.setAccuracyRingColor(Mapbox.getAndroidColor(options.accuracyColor));
2839
+ }
2840
+ if (options.accuracyRingColor !== undefined) {
2841
+ settings.setAccuracyRingBorderColor(Mapbox.getAndroidColor(options.accuracyRingColor));
2842
+ }
2843
+ if (options.pulsingColor !== undefined) {
2844
+ settings.setPulsingColor(Mapbox.getAndroidColor(options.pulsingColor));
2845
+ }
2846
+ return settings;
2847
+ }
2848
+ }));
2849
+ // if (typeof options.elevation != 'undefined') {
2850
+ // componentOptionsBuilder = componentOptionsBuilder.elevation(options.elevation);
2851
+ // }
2852
+ // if (typeof options.accuracyAlpha != 'undefined') {
2853
+ // componentOptionsBuilder = componentOptionsBuilder.accuracyAlpha(options.accuracyAlpha);
2854
+ // }
2855
+ // if (typeof options.foregroundTintColor != 'undefined') {
2856
+ // const foregroundTintColor = new java.lang.Integer(android.graphics.Color.parseColor(options.foregroundTintColor));
2857
+ // componentOptionsBuilder = componentOptionsBuilder.foregroundTintColor(foregroundTintColor);
2858
+ // }
2859
+ // if (typeof options.foregroundStaleTintColor != 'undefined') {
2860
+ // const foregroundStaleTintColor = new java.lang.Integer(android.graphics.Color.parseColor(options.foregroundStaleTintColor));
2861
+ // componentOptionsBuilder = componentOptionsBuilder.foregroundStaleTintColor(foregroundStaleTintColor);
2862
+ // }
2863
+ // if (typeof options.backgroundTintColor != 'undefined') {
2864
+ // const backgroundTintColor = new java.lang.Integer(android.graphics.Color.parseColor(options.backgroundTintColor));
2865
+ // componentOptionsBuilder = componentOptionsBuilder.backgroundTintColor(backgroundTintColor);
2866
+ // }
2867
+ // if (typeof options.bearingTintColor != 'undefined') {
2868
+ // const bearingTintColor = new java.lang.Integer(android.graphics.Color.parseColor(options.bearingTintColor));
2869
+ // componentOptionsBuilder = componentOptionsBuilder.bearingTintColor(bearingTintColor);
2870
+ // }
2871
+ // const componentOptions = componentOptionsBuilder.build();
2872
+ // this._locationComponent = this._mapboxMapInstance.getLocationComponent();
2873
+ // const activationOptionsBuilder = com.mapbox.maps.location.LocationComponentActivationOptions.builder(Utils.android.getApplicationContext(), this._mapboxMapInstance.getStyle());
2874
+ // activationOptionsBuilder.locationComponentOptions(componentOptions);
2875
+ // let useDefaultEngine = true;
2876
+ // if (typeof options.useDefaultLocationEngine != 'undefined') {
2877
+ // useDefaultEngine = options.useDefaultLocationEngine;
2878
+ // }
2879
+ // activationOptionsBuilder.useDefaultLocationEngine(useDefaultEngine);
2880
+ // const locationComponentActivationOptions = activationOptionsBuilder.build();
2881
+ // this._locationComponent.activateLocationComponent(locationComponentActivationOptions);
2882
+ // this._locationComponent.setLocationComponentEnabled(true);
2883
+ // let cameraMode = this._stringToCameraMode('TRACKING');
2884
+ // if (typeof options.cameraMode != 'undefined') {
2885
+ // cameraMode = this._stringToCameraMode(options.cameraMode);
2886
+ // }
2887
+ // this._locationComponent.setCameraMode(cameraMode);
2888
+ // let renderMode = com.mapbox.maps.location.modes.RenderMode.COMPASS;
2889
+ // if (typeof options.renderMode != 'undefined') {
2890
+ // renderMode = this._stringToRenderMode(options.renderMode);
2891
+ // }
2892
+ // this._locationComponent.setRenderMode(renderMode);
2893
+ // if (Trace.isEnabled()) {
2894
+ // CLog(CLogTypes.info, 'showUserLocationMarker(): after renderMode');
2895
+ // }
2896
+ // if (typeof options.clickListener != 'undefined') {
2897
+ // this.onLocationClickListener = new com.mapbox.maps.location.OnLocationClickListener({
2898
+ // onLocationComponentClick: () => {
2899
+ // options.clickListener();
2900
+ // }
2901
+ // });
2902
+ // this._locationComponent.addOnLocationClickListener(this.onLocationClickListener);
2903
+ // }
2904
+ // if (typeof options.cameraTrackingChangedListener != 'undefined') {
2905
+ // this._locationComponent.addOnCameraTrackingChangedListener(options.cameraTrackingChangedListener);
2906
+ // }
2907
+ }
2908
+ catch (ex) {
2909
+ if (Trace.isEnabled()) {
2910
+ CLog(CLogTypes.info, 'Error in mapbox.showUserLocationMarker: ' + ex);
2766
2911
  }
2767
- });
2912
+ throw ex;
2913
+ }
2768
2914
  }
2769
2915
  /**
2770
2916
  * hide (destroy) the user location marker
@@ -2781,14 +2927,15 @@ export class Mapbox extends MapboxCommon {
2781
2927
  reject('No map has been loaded');
2782
2928
  return;
2783
2929
  }
2784
- if (!this._locationComponent) {
2930
+ const locationPlugin = this._getPlugin('MAPBOX_LOCATION_COMPONENT_PLUGIN_ID');
2931
+ if (!locationPlugin) {
2785
2932
  if (Trace.isEnabled()) {
2786
2933
  CLog(CLogTypes.info, 'hideUserLocationMarker(): no location component is loaded.');
2787
2934
  }
2788
2935
  resolve();
2789
2936
  return;
2790
2937
  }
2791
- this._locationComponent.setLocationComponentEnabled(false);
2938
+ locationPlugin.setEnabled(false);
2792
2939
  resolve();
2793
2940
  }
2794
2941
  catch (ex) {
@@ -2808,41 +2955,47 @@ export class Mapbox extends MapboxCommon {
2808
2955
  * The marker must be configured using showUserLocationMarker before this method
2809
2956
  * can called.
2810
2957
  */
2811
- changeUserLocationMarkerMode(renderModeString, cameraModeString, nativeMap) {
2958
+ changeUserLocationMarkerMode(renderMode, cameraMode, nativeMap) {
2812
2959
  return new Promise((resolve, reject) => {
2813
2960
  try {
2814
- if (!this._locationComponent) {
2815
- reject('No location component has been loaded');
2816
- return;
2961
+ if (Trace.isEnabled()) {
2962
+ CLog(CLogTypes.info, 'showUserLocationMarker()');
2817
2963
  }
2818
- if (cameraModeString) {
2819
- const cameraMode = this._stringToCameraMode(cameraModeString);
2820
- if (Trace.isEnabled()) {
2821
- CLog(CLogTypes.info, `Mapbox::changeUserLocationMarkerMode(): current camera mode is: ${this._locationComponent.getCameraMode()}`);
2822
- CLog(CLogTypes.info, `Mapbox::changeUserLocationMarkerMode(): changing camera mode to: ${cameraMode}`);
2823
- }
2824
- this._locationComponent.setCameraMode(cameraMode);
2825
- if (Trace.isEnabled()) {
2826
- CLog(CLogTypes.info, `Mapbox::changeUserLocationMarkerMode(): new camera mode is: ${this._locationComponent.getCameraMode()}`);
2827
- }
2964
+ if (!this._mapboxMapInstance) {
2965
+ throw new Error('No map has been loaded');
2828
2966
  }
2829
- if (renderModeString) {
2830
- const renderMode = this._stringToRenderMode(renderModeString);
2831
- if (Trace.isEnabled()) {
2832
- CLog(CLogTypes.info, `Mapbox::changeUserLocationMarkerMode(): current render mode is: ${this._locationComponent.getRenderMode()}`);
2833
- CLog(CLogTypes.info, `Mapbox::changeUserLocationMarkerMode(): changing render mode to: '${renderMode}'`);
2967
+ if (!this.onIndicatorPositionChangedListener) {
2968
+ throw new Error('showUserLocationMarker must be used first');
2969
+ }
2970
+ const locationPlugin = this._getPlugin('MAPBOX_LOCATION_COMPONENT_PLUGIN_ID');
2971
+ if (this.onIndicatorPositionChangedListener) {
2972
+ locationPlugin.removeOnIndicatorPositionChangedListener(this.onIndicatorPositionChangedListener);
2973
+ }
2974
+ this.onIndicatorPositionChangedListener = new com.mapbox.maps.plugin.locationcomponent.OnIndicatorPositionChangedListener({
2975
+ onIndicatorPositionChanged: (point) => {
2976
+ this.lastKnownLocation = point;
2977
+ if (!cameraMode || cameraMode?.indexOf('TRACKING')) {
2978
+ this._mapboxMapInstance.setCamera(new com.mapbox.maps.CameraOptions.Builder().center(point).build());
2979
+ }
2834
2980
  }
2835
- this._locationComponent.setRenderMode(renderMode);
2836
- if (Trace.isEnabled()) {
2837
- CLog(CLogTypes.info, 'changeUserLocationMarkerMode(): new render mode is:', this._locationComponent.getRenderMode());
2981
+ });
2982
+ locationPlugin.addOnIndicatorPositionChangedListener(this.onIndicatorPositionChangedListener);
2983
+ locationPlugin.updateSettings(
2984
+ //@ts-ignore
2985
+ new kotlin.jvm.functions.Function1({
2986
+ invoke: (settings) => {
2987
+ settings.setEnabled(true);
2988
+ settings.setPulsingEnabled(true);
2989
+ settings.setPuckBearingEnabled(renderMode !== 'NORMAL');
2990
+ return settings;
2838
2991
  }
2839
- }
2992
+ }));
2840
2993
  }
2841
2994
  catch (ex) {
2842
2995
  if (Trace.isEnabled()) {
2843
2996
  CLog(CLogTypes.info, 'Error in mapbox.changeUserLocationMarkerMode: ' + ex);
2844
2997
  }
2845
- reject(ex);
2998
+ throw ex;
2846
2999
  }
2847
3000
  });
2848
3001
  }
@@ -2855,28 +3008,29 @@ export class Mapbox extends MapboxCommon {
2855
3008
  */
2856
3009
  forceUserLocationUpdate(location, nativeMap) {
2857
3010
  return new Promise((resolve, reject) => {
2858
- try {
2859
- if (Trace.isEnabled()) {
2860
- CLog(CLogTypes.info, 'forceUserLocation(): top');
2861
- }
2862
- if (!this._locationComponent) {
2863
- reject('No location component has been loaded');
2864
- return;
2865
- }
2866
- // the location object needs to be converted into an android location
2867
- const nativeLocation = new android.location.Location('background');
2868
- nativeLocation.setLatitude(location.latitude);
2869
- nativeLocation.setLongitude(location.longitude);
2870
- nativeLocation.setAltitude(location.altitude);
2871
- this._locationComponent.forceLocationUpdate(nativeLocation);
2872
- resolve();
2873
- }
2874
- catch (ex) {
2875
- if (Trace.isEnabled()) {
2876
- CLog(CLogTypes.info, 'Error in mapbox.forceUserLocationUpdate: ' + ex);
2877
- }
2878
- reject(ex);
2879
- }
3011
+ //TODO: is it possible?
3012
+ reject('Not supported anymore');
3013
+ // try {
3014
+ // if (Trace.isEnabled()) {
3015
+ // CLog(CLogTypes.info, 'forceUserLocation(): top');
3016
+ // }
3017
+ // if (!this._locationComponent) {
3018
+ // reject('No location component has been loaded');
3019
+ // return;
3020
+ // }
3021
+ // // the location object needs to be converted into an android location
3022
+ // const nativeLocation = new android.location.Location('background');
3023
+ // nativeLocation.setLatitude(location.latitude);
3024
+ // nativeLocation.setLongitude(location.longitude);
3025
+ // nativeLocation.setAltitude(location.altitude);
3026
+ // this._locationComponent.forceLocationUpdate(nativeLocation);
3027
+ // resolve();
3028
+ // } catch (ex) {
3029
+ // if (Trace.isEnabled()) {
3030
+ // CLog(CLogTypes.info, 'Error in mapbox.forceUserLocationUpdate: ' + ex);
3031
+ // }
3032
+ // reject(ex);
3033
+ // }
2880
3034
  });
2881
3035
  }
2882
3036
  getLayer(name, nativeMap) {
@@ -2887,8 +3041,10 @@ export class Mapbox extends MapboxCommon {
2887
3041
  reject('No map has been loaded');
2888
3042
  return;
2889
3043
  }
2890
- const styleLoadedCallback = new com.mapbox.mapboxsdk.maps.Style.OnStyleLoaded({
3044
+ const styleLoadedCallback = new com.mapbox.maps.Style.OnStyleLoaded({
2891
3045
  onStyleLoaded: (style) => {
3046
+ //TODO: fix declaration which is missing extension for this
3047
+ //@ts-ignore
2892
3048
  const layer = style.getLayer(name);
2893
3049
  resolve(layer ? new Layer(layer) : null);
2894
3050
  }
@@ -2911,12 +3067,15 @@ export class Mapbox extends MapboxCommon {
2911
3067
  reject('No map has been loaded');
2912
3068
  return;
2913
3069
  }
2914
- const styleLoadedCallback = new com.mapbox.mapboxsdk.maps.Style.OnStyleLoaded({
3070
+ const styleLoadedCallback = new com.mapbox.maps.Style.OnStyleLoaded({
2915
3071
  onStyleLoaded: (style) => {
2916
- const layers = style.getLayers();
3072
+ const layers = style.getStyleLayers();
2917
3073
  const result = [];
2918
3074
  for (let i = 0; i < layers.size(); i++) {
2919
- result.push(new Layer(layers.get(i)));
3075
+ const id = layers.get(i).getId();
3076
+ //TODO: fix declaration which is missing extension for this
3077
+ //@ts-ignore
3078
+ result.push(new Layer(style.getLayer(id)));
2920
3079
  }
2921
3080
  resolve(result);
2922
3081
  }
@@ -2932,78 +3091,63 @@ export class Mapbox extends MapboxCommon {
2932
3091
  });
2933
3092
  }
2934
3093
  _getClickedMarkerDetails(clicked) {
2935
- for (const m in this._markers) {
2936
- const cached = this._markers[m];
3094
+ for (let index = 0; index < this._markers.length; index++) {
3095
+ const cached = this._markers[index];
2937
3096
  if (
2938
3097
  // eslint-disable-next-line eqeqeq
2939
- cached.lat == clicked.getPosition().getLatitude() &&
3098
+ cached.lat == clicked.position.latitude() &&
2940
3099
  // eslint-disable-next-line eqeqeq
2941
- cached.lng == clicked.getPosition().getLongitude() &&
3100
+ cached.lng == clicked.position.longitude() &&
2942
3101
  // eslint-disable-next-line eqeqeq
2943
- cached.title == clicked.getTitle() && // == because of null vs undefined
3102
+ cached.title == clicked.title && // == because of null vs undefined
2944
3103
  // eslint-disable-next-line eqeqeq
2945
- cached.subtitle == clicked.getSnippet()) {
3104
+ cached.subtitle == clicked.snippet) {
2946
3105
  return cached;
2947
3106
  }
2948
3107
  }
2949
3108
  }
2950
- _downloadImage(marker) {
2951
- return new Promise((resolve, reject) => {
2952
- // to cache..
2953
- if (this._markerIconDownloadCache[marker.icon]) {
2954
- marker.iconDownloaded = this._markerIconDownloadCache[marker.icon];
2955
- resolve(marker);
2956
- return;
2957
- }
2958
- // ..or not to cache
2959
- Http.getImage(marker.icon).then((output) => {
2960
- marker.iconDownloaded = output.android;
2961
- this._markerIconDownloadCache[marker.icon] = marker.iconDownloaded;
2962
- resolve(marker);
2963
- }, (e) => {
2964
- console.error(`Download failed for ' ${marker.icon}' with error: ${e}`);
2965
- resolve(marker);
2966
- });
2967
- });
3109
+ async _downloadImage(marker) {
3110
+ // to cache..
3111
+ if (this._markerIconDownloadCache[marker.icon]) {
3112
+ marker.downloadedIcon = this._markerIconDownloadCache[marker.icon];
3113
+ return marker;
3114
+ }
3115
+ // ..or not to cache
3116
+ try {
3117
+ const output = await Http.getImage(marker.icon);
3118
+ this._markerIconDownloadCache[marker.icon] = marker.downloadedIcon = output;
3119
+ return marker;
3120
+ }
3121
+ catch (error) {
3122
+ console.error(error);
3123
+ }
2968
3124
  }
2969
- _downloadMarkerImages(markers) {
2970
- const iterations = [];
3125
+ async _downloadMarkerImages(markers) {
2971
3126
  const result = [];
2972
3127
  for (let i = 0; i < markers.length; i++) {
2973
3128
  const marker = markers[i];
2974
3129
  if (marker.icon && marker.icon.startsWith('http')) {
2975
- const p = this._downloadImage(marker).then((mark) => {
2976
- result.push(mark);
2977
- });
2978
- iterations.push(p);
3130
+ const mark = await this._downloadImage(marker);
3131
+ result.push(mark);
2979
3132
  }
2980
3133
  else {
2981
3134
  result.push(marker);
2982
3135
  }
2983
3136
  }
2984
- return Promise.all(iterations).then((output) => result);
3137
+ return result;
2985
3138
  }
2986
3139
  project(data) {
2987
- const mapboxPoint = new com.mapbox.mapboxsdk.geometry.LatLng(data.lat, data.lng);
2988
- const screenLocation = this._mapboxMapInstance.getProjection().toScreenLocation(mapboxPoint);
2989
- return { x: Utils.layout.toDeviceIndependentPixels(screenLocation.x), y: Utils.layout.toDeviceIndependentPixels(screenLocation.y) };
3140
+ const mapboxPoint = com.mapbox.geojson.Point.fromLngLat(data.lng, data.lat);
3141
+ const screenLocation = this._mapboxMapInstance.pixelForCoordinate(mapboxPoint);
3142
+ return { x: Utils.layout.toDeviceIndependentPixels(screenLocation.getX()), y: Utils.layout.toDeviceIndependentPixels(screenLocation.getY()) };
2990
3143
  }
2991
3144
  projectBack(screenCoordinate) {
2992
- const pointf = new android.graphics.PointF(screenCoordinate.x, screenCoordinate.y);
2993
- const coordinate = this._mapboxMapInstance.getProjection().fromScreenLocation(pointf);
3145
+ const pointf = new com.mapbox.maps.ScreenCoordinate(screenCoordinate.x, screenCoordinate.y);
3146
+ const coordinate = this._mapboxMapInstance.coordinateForPixel(pointf);
2994
3147
  return {
2995
- lat: coordinate.getLatitude(),
2996
- lng: coordinate.getLongitude()
3148
+ lat: coordinate.latitude(),
3149
+ lng: coordinate.longitude()
2997
3150
  };
2998
3151
  }
2999
- getUserLocationCameraMode(nativeMap) {
3000
- if (!this._mapboxMapInstance) {
3001
- return 'NONE';
3002
- }
3003
- if (!this._locationComponent) {
3004
- return 'NONE';
3005
- }
3006
- return this._convertCameraMode(this._locationComponent.getCameraMode());
3007
- }
3008
3152
  }
3009
3153
  //# sourceMappingURL=index.android.js.map