summaryrefslogtreecommitdiff
path: root/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/NativeMapView.java
blob: d72e1a74a9b2b8eaf1f4d4743d91f6b615d65c6c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
package com.mapbox.mapboxsdk.maps;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.PointF;
import android.graphics.RectF;
import android.os.AsyncTask;
import android.os.Handler;
import android.support.annotation.IntRange;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import com.mapbox.geojson.Feature;
import com.mapbox.geojson.Geometry;
import com.mapbox.mapboxsdk.LibraryLoader;
import com.mapbox.mapboxsdk.annotations.Icon;
import com.mapbox.mapboxsdk.annotations.Marker;
import com.mapbox.mapboxsdk.annotations.Polygon;
import com.mapbox.mapboxsdk.annotations.Polyline;
import com.mapbox.mapboxsdk.camera.CameraPosition;
import com.mapbox.mapboxsdk.exceptions.CalledFromWorkerThreadException;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.geometry.LatLngBounds;
import com.mapbox.mapboxsdk.geometry.ProjectedMeters;
import com.mapbox.mapboxsdk.maps.renderer.MapRenderer;
import com.mapbox.mapboxsdk.storage.FileSource;
import com.mapbox.mapboxsdk.style.expressions.Expression;
import com.mapbox.mapboxsdk.style.layers.CannotAddLayerException;
import com.mapbox.mapboxsdk.style.layers.Layer;
import com.mapbox.mapboxsdk.style.light.Light;
import com.mapbox.mapboxsdk.style.sources.CannotAddSourceException;
import com.mapbox.mapboxsdk.style.sources.Source;
import com.mapbox.mapboxsdk.utils.BitmapUtils;
import timber.log.Timber;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

// Class that wraps the native methods for convenience
final class NativeMapView {

  //Hold a reference to prevent it from being GC'd as long as it's used on the native side
  private final FileSource fileSource;

  // Used to schedule work on the MapRenderer Thread
  private final MapRenderer mapRenderer;

  // Used to validate if methods are called from the correct thread
  private final Thread thread;

  // Used for callbacks
  private ViewCallback viewCallback;

  // Device density
  private final float pixelRatio;

  // Flag to indicating destroy was called
  private boolean destroyed = false;

  // Holds the pointer to JNI NativeMapView
  private long nativePtr = 0;

  // Listener invoked to return a bitmap of the map
  private MapboxMap.SnapshotReadyCallback snapshotReadyCallback;

  private final CopyOnWriteArrayList<MapView.OnMapChangedListener> onMapChangedListeners = new CopyOnWriteArrayList<>();

  static {
    LibraryLoader.load();
  }

  //
  // Constructors
  //

  public NativeMapView(final Context context, final ViewCallback viewCallback, final MapRenderer mapRenderer) {
    this(context, context.getResources().getDisplayMetrics().density, viewCallback, mapRenderer);
  }

  public NativeMapView(final Context context, float pixelRatio,
                       final ViewCallback viewCallback, final MapRenderer mapRenderer) {
    this.mapRenderer = mapRenderer;
    this.viewCallback = viewCallback;
    this.fileSource = FileSource.getInstance(context);
    this.pixelRatio = pixelRatio;
    this.thread = Thread.currentThread();
    nativeInitialize(this, fileSource, mapRenderer, pixelRatio);
  }

  //
  // Methods
  //

  private boolean checkState(String callingMethod) {
    // validate if invocation has occurred on the main thread
    if (thread != Thread.currentThread()) {
      throw new CalledFromWorkerThreadException(
        String.format(
          "Map interactions should happen on the UI thread. Method invoked from wrong thread is %s.",
          callingMethod)
      );
    }

    // validate if map has already been destroyed
    if (destroyed && !TextUtils.isEmpty(callingMethod)) {
      Timber.e(
        "You're calling `%s` after the `MapView` was destroyed, were you invoking it after `onDestroy()`?",
        callingMethod
      );
    }
    return destroyed;
  }

  public void destroy() {
    destroyed = true;
    onMapChangedListeners.clear();
    viewCallback = null;
    nativeDestroy();
  }

  public void update() {
    if (checkState("update")) {
      return;
    }

    mapRenderer.requestRender();
  }

  public void resizeView(int width, int height) {
    if (checkState("resizeView")) {
      return;
    }
    width = (int) (width / pixelRatio);
    height = (int) (height / pixelRatio);

    if (width < 0) {
      throw new IllegalArgumentException("width cannot be negative.");
    }

    if (height < 0) {
      throw new IllegalArgumentException("height cannot be negative.");
    }

    if (width > 65535) {
      // we have seen edge cases where devices return incorrect values #6111
      Timber.e("Device returned an out of range width size, "
        + "capping value at 65535 instead of %s", width);
      width = 65535;
    }

    if (height > 65535) {
      // we have seen edge cases where devices return incorrect values #6111
      Timber.e("Device returned an out of range height size, "
        + "capping value at 65535 instead of %s", height);
      height = 65535;
    }

    nativeResizeView(width, height);
  }

  public void setStyleUrl(String url) {
    if (checkState("setStyleUrl")) {
      return;
    }
    nativeSetStyleUrl(url);
  }

  public String getStyleUrl() {
    if (checkState("getStyleUrl")) {
      return null;
    }
    return nativeGetStyleUrl();
  }

  public void setStyleJson(String newStyleJson) {
    if (checkState("setStyleJson")) {
      return;
    }
    nativeSetStyleJson(newStyleJson);
  }

  public String getStyleJson() {
    if (checkState("getStyleJson")) {
      return null;
    }
    return nativeGetStyleJson();
  }

  public void setLatLngBounds(LatLngBounds latLngBounds) {
    if (checkState("setLatLngBounds")) {
      return;
    }
    nativeSetLatLngBounds(latLngBounds);
  }

  public void cancelTransitions() {
    if (checkState("cancelTransitions")) {
      return;
    }
    nativeCancelTransitions();
  }

  public void setGestureInProgress(boolean inProgress) {
    if (checkState("setGestureInProgress")) {
      return;
    }
    nativeSetGestureInProgress(inProgress);
  }

  public void moveBy(double dx, double dy) {
    if (checkState("moveBy")) {
      return;
    }
    moveBy(dx, dy, 0);
  }

  public void moveBy(double dx, double dy, long duration) {
    if (checkState("moveBy")) {
      return;
    }
    nativeMoveBy(dx / pixelRatio, dy / pixelRatio, duration);
  }

  public void setLatLng(LatLng latLng) {
    if (checkState("setLatLng")) {
      return;
    }
    setLatLng(latLng, 0);
  }

  public void setLatLng(LatLng latLng, long duration) {
    if (checkState("setLatLng")) {
      return;
    }
    nativeSetLatLng(latLng.getLatitude(), latLng.getLongitude(), duration);
  }

  public LatLng getLatLng() {
    if (checkState("")) {
      return new LatLng();
    }
    // wrap longitude values coming from core
    return nativeGetLatLng().wrap();
  }

  public CameraPosition getCameraForLatLngBounds(LatLngBounds latLngBounds, int[] padding) {
    if (checkState("getCameraForLatLngBounds")) {
      return null;
    }
    return nativeGetCameraForLatLngBounds(
      latLngBounds,
      padding[1] / pixelRatio,
      padding[0] / pixelRatio,
      padding[3] / pixelRatio,
      padding[2] / pixelRatio);
  }

  public CameraPosition getCameraForGeometry(Geometry geometry, double bearing, int[] padding) {
    if (checkState("getCameraForGeometry")) {
      return null;
    }
    return nativeGetCameraForGeometry(
      geometry, bearing,
      padding[1] / pixelRatio,
      padding[0] / pixelRatio,
      padding[3] / pixelRatio,
      padding[2] / pixelRatio);
  }

  public void resetPosition() {
    if (checkState("resetPosition")) {
      return;
    }
    nativeResetPosition();
  }

  public double getPitch() {
    if (checkState("getPitch")) {
      return 0;
    }
    return nativeGetPitch();
  }

  public void setPitch(double pitch, long duration) {
    if (checkState("setPitch")) {
      return;
    }
    nativeSetPitch(pitch, duration);
  }

  public void setZoom(double zoom, PointF focalPoint, long duration) {
    if (checkState("setZoom")) {
      return;
    }
    nativeSetZoom(zoom, focalPoint.x / pixelRatio, focalPoint.y / pixelRatio, duration);
  }

  public double getZoom() {
    if (checkState("getZoom")) {
      return 0;
    }
    return nativeGetZoom();
  }

  public void resetZoom() {
    if (checkState("resetZoom")) {
      return;
    }
    nativeResetZoom();
  }

  public void setMinZoom(double zoom) {
    if (checkState("setMinZoom")) {
      return;
    }
    nativeSetMinZoom(zoom);
  }

  public double getMinZoom() {
    if (checkState("getMinZoom")) {
      return 0;
    }
    return nativeGetMinZoom();
  }

  public void setMaxZoom(double zoom) {
    if (checkState("setMaxZoom")) {
      return;
    }
    nativeSetMaxZoom(zoom);
  }

  public double getMaxZoom() {
    if (checkState("getMaxZoom")) {
      return 0;
    }
    return nativeGetMaxZoom();
  }

  public void rotateBy(double sx, double sy, double ex, double ey) {
    if (checkState("rotateBy")) {
      return;
    }
    rotateBy(sx, sy, ex, ey, 0);
  }

  public void rotateBy(double sx, double sy, double ex, double ey,
                       long duration) {
    if (checkState("rotateBy")) {
      return;
    }
    nativeRotateBy(sx / pixelRatio, sy / pixelRatio, ex, ey, duration);
  }

  public void setContentPadding(int[] padding) {
    if (checkState("setContentPadding")) {
      return;
    }
    nativeSetContentPadding(
      padding[1] / pixelRatio,
      padding[0] / pixelRatio,
      padding[3] / pixelRatio,
      padding[2] / pixelRatio);
  }

  public void setBearing(double degrees) {
    if (checkState("setBearing")) {
      return;
    }
    setBearing(degrees, 0);
  }

  public void setBearing(double degrees, long duration) {
    if (checkState("setBearing")) {
      return;
    }
    nativeSetBearing(degrees, duration);
  }

  public void setBearing(double degrees, double cx, double cy) {
    if (checkState("setBearing")) {
      return;
    }
    setBearing(degrees, cx, cy, 0);
  }

  public void setBearing(double degrees, double fx, double fy, long duration) {
    if (checkState("setBearing")) {
      return;
    }
    nativeSetBearingXY(degrees, fx / pixelRatio, fy / pixelRatio, duration);
  }

  public double getBearing() {
    if (checkState("getBearing")) {
      return 0;
    }
    return nativeGetBearing();
  }

  public void resetNorth() {
    if (checkState("resetNorth")) {
      return;
    }
    nativeResetNorth();
  }

  public long addMarker(Marker marker) {
    if (checkState("addMarker")) {
      return 0;
    }
    Marker[] markers = {marker};
    return nativeAddMarkers(markers)[0];
  }

  public long[] addMarkers(List<Marker> markers) {
    if (checkState("addMarkers")) {
      return new long[] {};
    }
    return nativeAddMarkers(markers.toArray(new Marker[markers.size()]));
  }

  public long addPolyline(Polyline polyline) {
    if (checkState("addPolyline")) {
      return 0;
    }
    Polyline[] polylines = {polyline};
    return nativeAddPolylines(polylines)[0];
  }

  public long[] addPolylines(List<Polyline> polylines) {
    if (checkState("addPolylines")) {
      return new long[] {};
    }
    return nativeAddPolylines(polylines.toArray(new Polyline[polylines.size()]));
  }

  public long addPolygon(Polygon polygon) {
    if (checkState("addPolygon")) {
      return 0;
    }
    Polygon[] polygons = {polygon};
    return nativeAddPolygons(polygons)[0];
  }

  public long[] addPolygons(List<Polygon> polygons) {
    if (checkState("addPolygons")) {
      return new long[] {};
    }
    return nativeAddPolygons(polygons.toArray(new Polygon[polygons.size()]));
  }

  public void updateMarker(Marker marker) {
    if (checkState("updateMarker")) {
      return;
    }
    LatLng position = marker.getPosition();
    Icon icon = marker.getIcon();
    nativeUpdateMarker(marker.getId(), position.getLatitude(), position.getLongitude(), icon.getId());
  }

  public void updatePolygon(Polygon polygon) {
    if (checkState("updatePolygon")) {
      return;
    }
    nativeUpdatePolygon(polygon.getId(), polygon);
  }

  public void updatePolyline(Polyline polyline) {
    if (checkState("updatePolyline")) {
      return;
    }
    nativeUpdatePolyline(polyline.getId(), polyline);
  }

  public void removeAnnotation(long id) {
    if (checkState("removeAnnotation")) {
      return;
    }
    long[] ids = {id};
    removeAnnotations(ids);
  }

  public void removeAnnotations(long[] ids) {
    if (checkState("removeAnnotations")) {
      return;
    }
    nativeRemoveAnnotations(ids);
  }

  public long[] queryPointAnnotations(RectF rect) {
    if (checkState("queryPointAnnotations")) {
      return new long[] {};
    }
    return nativeQueryPointAnnotations(rect);
  }

  public long[] queryShapeAnnotations(RectF rectF) {
    if (checkState("queryShapeAnnotations")) {
      return new long[] {};
    }
    return nativeQueryShapeAnnotations(rectF);
  }

  public void addAnnotationIcon(String symbol, int width, int height, float scale, byte[] pixels) {
    if (checkState("addAnnotationIcon")) {
      return;
    }
    nativeAddAnnotationIcon(symbol, width, height, scale, pixels);
  }

  public void removeAnnotationIcon(String symbol) {
    if (checkState("removeAnnotationIcon")) {
      return;
    }
    nativeRemoveAnnotationIcon(symbol);
  }

  public void setVisibleCoordinateBounds(LatLng[] coordinates, RectF padding, double direction, long duration) {
    if (checkState("setVisibleCoordinateBounds")) {
      return;
    }
    nativeSetVisibleCoordinateBounds(coordinates, padding, direction, duration);
  }

  public void onLowMemory() {
    if (checkState("onLowMemory")) {
      return;
    }
    nativeOnLowMemory();
  }

  public void setDebug(boolean debug) {
    if (checkState("setDebug")) {
      return;
    }
    nativeSetDebug(debug);
  }

  public void cycleDebugOptions() {
    if (checkState("cycleDebugOptions")) {
      return;
    }
    nativeCycleDebugOptions();
  }

  public boolean getDebug() {
    if (checkState("getDebug")) {
      return false;
    }
    return nativeGetDebug();
  }

  public boolean isFullyLoaded() {
    if (checkState("isFullyLoaded")) {
      return false;
    }
    return nativeIsFullyLoaded();
  }

  public void setReachability(boolean status) {
    if (checkState("setReachability")) {
      return;
    }
    nativeSetReachability(status);
  }

  public double getMetersPerPixelAtLatitude(double lat) {
    if (checkState("getMetersPerPixelAtLatitude")) {
      return 0;
    }
    return nativeGetMetersPerPixelAtLatitude(lat, getZoom()) / pixelRatio;
  }

  public ProjectedMeters projectedMetersForLatLng(LatLng latLng) {
    if (checkState("projectedMetersForLatLng")) {
      return null;
    }
    return nativeProjectedMetersForLatLng(latLng.getLatitude(), latLng.getLongitude());
  }

  public LatLng latLngForProjectedMeters(ProjectedMeters projectedMeters) {
    if (checkState("latLngForProjectedMeters")) {
      return new LatLng();
    }
    return nativeLatLngForProjectedMeters(projectedMeters.getNorthing(),
      projectedMeters.getEasting()).wrap();
  }

  public PointF pixelForLatLng(LatLng latLng) {
    if (checkState("pixelForLatLng")) {
      return new PointF();
    }
    PointF pointF = nativePixelForLatLng(latLng.getLatitude(), latLng.getLongitude());
    pointF.set(pointF.x * pixelRatio, pointF.y * pixelRatio);
    return pointF;
  }

  public LatLng latLngForPixel(PointF pixel) {
    if (checkState("latLngForPixel")) {
      return new LatLng();
    }
    return nativeLatLngForPixel(pixel.x / pixelRatio, pixel.y / pixelRatio).wrap();
  }

  public double getTopOffsetPixelsForAnnotationSymbol(String symbolName) {
    if (checkState("getTopOffsetPixelsForAnnotationSymbol")) {
      return 0;
    }
    return nativeGetTopOffsetPixelsForAnnotationSymbol(symbolName);
  }

  public void jumpTo(double angle, LatLng center, double pitch, double zoom) {
    if (checkState("jumpTo")) {
      return;
    }
    nativeJumpTo(angle, center.getLatitude(), center.getLongitude(), pitch, zoom);
  }

  public void easeTo(double angle, LatLng center, long duration, double pitch, double zoom,
                     boolean easingInterpolator) {
    if (checkState("easeTo")) {
      return;
    }
    nativeEaseTo(angle, center.getLatitude(), center.getLongitude(), duration, pitch, zoom,
      easingInterpolator);
  }

  public void flyTo(double angle, LatLng center, long duration, double pitch, double zoom) {
    if (checkState("flyTo")) {
      return;
    }
    nativeFlyTo(angle, center.getLatitude(), center.getLongitude(), duration, pitch, zoom);
  }

  public CameraPosition getCameraPosition() {
    if (checkState("getCameraValues")) {
      return new CameraPosition.Builder().build();
    }
    return nativeGetCameraPosition();
  }

  public void setPrefetchesTiles(boolean enable) {
    if (checkState("setPrefetchesTiles")) {
      return;
    }
    nativeSetPrefetchesTiles(enable);
  }

  public boolean getPrefetchesTiles() {
    if (checkState("getPrefetchesTiles")) {
      return false;
    }
    return nativeGetPrefetchesTiles();
  }

  // Runtime style Api

  public long getTransitionDuration() {
    return nativeGetTransitionDuration();
  }

  public void setTransitionDuration(long duration) {
    nativeSetTransitionDuration(duration);
  }

  public long getTransitionDelay() {
    return nativeGetTransitionDelay();
  }

  public void setTransitionDelay(long delay) {
    nativeSetTransitionDelay(delay);
  }

  public List<Layer> getLayers() {
    if (checkState("getLayers")) {
      return null;
    }
    return Arrays.asList(nativeGetLayers());
  }

  public Layer getLayer(String layerId) {
    if (checkState("getLayer")) {
      return null;
    }
    return nativeGetLayer(layerId);
  }

  public void addLayer(@NonNull Layer layer) {
    if (checkState("addLayer")) {
      return;
    }
    nativeAddLayer(layer.getNativePtr(), null);
  }

  public void addLayerBelow(@NonNull Layer layer, @NonNull String below) {
    if (checkState("addLayerBelow")) {
      return;
    }
    nativeAddLayer(layer.getNativePtr(), below);
  }

  public void addLayerAbove(@NonNull Layer layer, @NonNull String above) {
    if (checkState("addLayerAbove")) {
      return;
    }
    nativeAddLayerAbove(layer.getNativePtr(), above);
  }

  public void addLayerAt(@NonNull Layer layer, @IntRange(from = 0) int index) {
    if (checkState("addLayerAt")) {
      return;
    }
    nativeAddLayerAt(layer.getNativePtr(), index);
  }

  @Nullable
  public Layer removeLayer(@NonNull String layerId) {
    if (checkState("removeLayer")) {
      return null;
    }
    return nativeRemoveLayerById(layerId);
  }

  @Nullable
  public Layer removeLayer(@NonNull Layer layer) {
    if (checkState("removeLayer")) {
      return null;
    }
    nativeRemoveLayer(layer.getNativePtr());
    return layer;
  }

  @Nullable
  public Layer removeLayerAt(@IntRange(from = 0) int index) {
    if (checkState("removeLayerAt")) {
      return null;
    }
    return nativeRemoveLayerAt(index);
  }

  public List<Source> getSources() {
    if (checkState("getSources")) {
      return null;
    }
    return Arrays.asList(nativeGetSources());
  }

  public Source getSource(@NonNull String sourceId) {
    if (checkState("getSource")) {
      return null;
    }
    return nativeGetSource(sourceId);
  }

  public void addSource(@NonNull Source source) {
    if (checkState("addSource")) {
      return;
    }
    nativeAddSource(source, source.getNativePtr());
  }

  @Nullable
  public Source removeSource(@NonNull String sourceId) {
    if (checkState("removeSource")) {
      return null;
    }
    Source source = getSource(sourceId);
    if (source != null) {
      return removeSource(source);
    }
    return null;
  }

  @Nullable
  public Source removeSource(@NonNull Source source) {
    if (checkState("removeSource")) {
      return null;
    }
    nativeRemoveSource(source, source.getNativePtr());
    return source;
  }

  public void addImage(@NonNull String name, @NonNull Bitmap image) {
    if (checkState("addImage")) {
      return;
    }

    // Determine pixel ratio, cast to float to avoid rounding, see mapbox-gl-native/issues/11809
    float pixelRatio = (float) image.getDensity() / DisplayMetrics.DENSITY_DEFAULT;
    nativeAddImage(name, image, pixelRatio);
  }

  public void addImages(@NonNull HashMap<String, Bitmap> bitmapHashMap) {
    if (checkState("addImages")) {
      return;
    }
    //noinspection unchecked
    new BitmapImageConversionTask(this).execute(bitmapHashMap);
  }

  public void removeImage(String name) {
    if (checkState("removeImage")) {
      return;
    }
    nativeRemoveImage(name);
  }

  public Bitmap getImage(String name) {
    if (checkState("getImage")) {
      return null;
    }
    return nativeGetImage(name);
  }

  // Feature querying

  @NonNull
  public List<Feature> queryRenderedFeatures(@NonNull PointF coordinates,
                                             @Nullable String[] layerIds,
                                             @Nullable Expression filter) {
    if (checkState("queryRenderedFeatures")) {
      return new ArrayList<>();
    }
    Feature[] features = nativeQueryRenderedFeaturesForPoint(coordinates.x / pixelRatio,
      coordinates.y / pixelRatio, layerIds, filter != null ? filter.toArray() : null);
    return features != null ? Arrays.asList(features) : new ArrayList<Feature>();
  }

  @NonNull
  public List<Feature> queryRenderedFeatures(@NonNull RectF coordinates,
                                             @Nullable String[] layerIds,
                                             @Nullable Expression filter) {
    if (checkState("queryRenderedFeatures")) {
      return new ArrayList<>();
    }
    Feature[] features = nativeQueryRenderedFeaturesForBox(
      coordinates.left / pixelRatio,
      coordinates.top / pixelRatio,
      coordinates.right / pixelRatio,
      coordinates.bottom / pixelRatio,
      layerIds,
      filter != null ? filter.toArray() : null);
    return features != null ? Arrays.asList(features) : new ArrayList<Feature>();
  }

  public void setApiBaseUrl(String baseUrl) {
    if (checkState("setApiBaseUrl")) {
      return;
    }
    fileSource.setApiBaseUrl(baseUrl);
  }

  public Light getLight() {
    if (checkState("getLight")) {
      return null;
    }
    return nativeGetLight();
  }

  public float getPixelRatio() {
    return pixelRatio;
  }

  RectF getDensityDependantRectangle(final RectF rectangle) {
    return new RectF(
      rectangle.left / pixelRatio,
      rectangle.top / pixelRatio,
      rectangle.right / pixelRatio,
      rectangle.bottom / pixelRatio
    );
  }

  //
  // Callbacks
  //

  protected void onMapChanged(int rawChange) {
    for (MapView.OnMapChangedListener onMapChangedListener : onMapChangedListeners) {
      try {
        onMapChangedListener.onMapChanged(rawChange);
      } catch (RuntimeException err) {
        Timber.e(err, "Exception in MapView.OnMapChangedListener");
      }
    }
  }

  protected void onSnapshotReady(Bitmap mapContent) {
    if (checkState("OnSnapshotReady")) {
      return;
    }

    Bitmap viewContent = viewCallback.getViewContent();
    if (snapshotReadyCallback != null && mapContent != null && viewContent != null) {
      snapshotReadyCallback.onSnapshotReady(BitmapUtils.mergeBitmap(mapContent, viewContent));
    }
  }

  //
  // JNI methods
  //

  private native void nativeInitialize(NativeMapView nativeMapView,
                                       FileSource fileSource,
                                       MapRenderer mapRenderer,
                                       float pixelRatio);

  private native void nativeDestroy();

  private native void nativeResizeView(int width, int height);

  private native void nativeSetStyleUrl(String url);

  private native String nativeGetStyleUrl();

  private native void nativeSetStyleJson(String newStyleJson);

  private native String nativeGetStyleJson();

  private native void nativeSetLatLngBounds(LatLngBounds latLngBounds);

  private native void nativeCancelTransitions();

  private native void nativeSetGestureInProgress(boolean inProgress);

  private native void nativeMoveBy(double dx, double dy, long duration);

  private native void nativeSetLatLng(double latitude, double longitude, long duration);

  private native LatLng nativeGetLatLng();

  private native CameraPosition nativeGetCameraForLatLngBounds(
    LatLngBounds latLngBounds, double top, double left, double bottom, double right);

  private native CameraPosition nativeGetCameraForGeometry(
    Geometry geometry, double bearing, double top, double left, double bottom, double right);

  private native void nativeResetPosition();

  private native double nativeGetPitch();

  private native void nativeSetPitch(double pitch, long duration);

  private native void nativeSetZoom(double zoom, double cx, double cy, long duration);

  private native double nativeGetZoom();

  private native void nativeResetZoom();

  private native void nativeSetMinZoom(double zoom);

  private native double nativeGetMinZoom();

  private native void nativeSetMaxZoom(double zoom);

  private native double nativeGetMaxZoom();

  private native void nativeRotateBy(double sx, double sy, double ex, double ey, long duration);

  private native void nativeSetContentPadding(double top, double left, double bottom, double right);

  private native void nativeSetBearing(double degrees, long duration);

  private native void nativeSetBearingXY(double degrees, double fx, double fy, long duration);

  private native double nativeGetBearing();

  private native void nativeResetNorth();

  private native void nativeUpdateMarker(long markerId, double lat, double lon, String iconId);

  private native long[] nativeAddMarkers(Marker[] markers);

  private native long[] nativeAddPolylines(Polyline[] polylines);

  private native long[] nativeAddPolygons(Polygon[] polygons);

  private native void nativeRemoveAnnotations(long[] id);

  private native long[] nativeQueryPointAnnotations(RectF rect);

  private native long[] nativeQueryShapeAnnotations(RectF rect);

  private native void nativeAddAnnotationIcon(String symbol, int width, int height, float scale, byte[] pixels);

  private native void nativeRemoveAnnotationIcon(String symbol);

  private native void nativeSetVisibleCoordinateBounds(LatLng[] coordinates, RectF padding,
                                                       double direction, long duration);

  private native void nativeOnLowMemory();

  private native void nativeSetDebug(boolean debug);

  private native void nativeCycleDebugOptions();

  private native boolean nativeGetDebug();

  private native boolean nativeIsFullyLoaded();

  private native void nativeSetReachability(boolean status);

  private native double nativeGetMetersPerPixelAtLatitude(double lat, double zoom);

  private native ProjectedMeters nativeProjectedMetersForLatLng(double latitude, double longitude);

  private native LatLng nativeLatLngForProjectedMeters(double northing, double easting);

  private native PointF nativePixelForLatLng(double lat, double lon);

  private native LatLng nativeLatLngForPixel(float x, float y);

  private native double nativeGetTopOffsetPixelsForAnnotationSymbol(String symbolName);

  private native void nativeJumpTo(double angle, double latitude, double longitude, double pitch, double zoom);

  private native void nativeEaseTo(double angle, double latitude, double longitude,
                                   long duration, double pitch, double zoom,
                                   boolean easingInterpolator);

  private native void nativeFlyTo(double angle, double latitude, double longitude,
                                  long duration, double pitch, double zoom);

  private native CameraPosition nativeGetCameraPosition();

  private native long nativeGetTransitionDuration();

  private native void nativeSetTransitionDuration(long duration);

  private native long nativeGetTransitionDelay();

  private native void nativeSetTransitionDelay(long delay);

  private native Layer[] nativeGetLayers();

  private native Layer nativeGetLayer(String layerId);

  private native void nativeAddLayer(long layerPtr, String before) throws CannotAddLayerException;

  private native void nativeAddLayerAbove(long layerPtr, String above) throws CannotAddLayerException;

  private native void nativeAddLayerAt(long layerPtr, int index) throws CannotAddLayerException;

  private native Layer nativeRemoveLayerById(String layerId);

  private native void nativeRemoveLayer(long layerId);

  private native Layer nativeRemoveLayerAt(int index);

  private native Source[] nativeGetSources();

  private native Source nativeGetSource(String sourceId);

  private native void nativeAddSource(Source source, long sourcePtr) throws CannotAddSourceException;

  private native void nativeRemoveSource(Source source, long sourcePtr);

  private native void nativeAddImage(String name, Bitmap bitmap, float pixelRatio);

  private native void nativeAddImages(Image[] images);

  private native void nativeRemoveImage(String name);

  private native Bitmap nativeGetImage(String name);

  private native void nativeUpdatePolygon(long polygonId, Polygon polygon);

  private native void nativeUpdatePolyline(long polylineId, Polyline polyline);

  private native void nativeTakeSnapshot();

  private native Feature[] nativeQueryRenderedFeaturesForPoint(float x, float y,
                                                               String[] layerIds,
                                                               Object[] filter);

  private native Feature[] nativeQueryRenderedFeaturesForBox(float left, float top,
                                                             float right, float bottom,
                                                             String[] layerIds,
                                                             Object[] filter);

  private native Light nativeGetLight();

  private native void nativeSetPrefetchesTiles(boolean enable);

  private native boolean nativeGetPrefetchesTiles();

  int getWidth() {
    if (checkState("")) {
      return 0;
    }
    return viewCallback.getWidth();
  }

  int getHeight() {
    if (checkState("")) {
      return 0;
    }
    return viewCallback.getHeight();
  }

  //
  // MapChangeEvents
  //

  void addOnMapChangedListener(@NonNull MapView.OnMapChangedListener listener) {
    onMapChangedListeners.add(listener);
  }

  void removeOnMapChangedListener(@NonNull MapView.OnMapChangedListener listener) {
    if (onMapChangedListeners.contains(listener)) {
      onMapChangedListeners.remove(listener);
    }
  }

  //
  // Snapshot
  //

  void addSnapshotCallback(@NonNull MapboxMap.SnapshotReadyCallback callback) {
    if (checkState("addSnapshotCallback")) {
      return;
    }
    snapshotReadyCallback = callback;
    nativeTakeSnapshot();
  }

  public void setOnFpsChangedListener(final MapboxMap.OnFpsChangedListener listener) {
    final Handler handler = new Handler();
    mapRenderer.queueEvent(new Runnable() {

      @Override
      public void run() {
        mapRenderer.setOnFpsChangedListener(new MapboxMap.OnFpsChangedListener() {
          @Override
          public void onFpsChanged(final double fps) {
            handler.post(new Runnable() {

              @Override
              public void run() {
                listener.onFpsChanged(fps);
              }

            });
          }
        });
      }

    });
  }

  //
  // Image conversion
  //

  private static class BitmapImageConversionTask extends AsyncTask<HashMap<String, Bitmap>, Void, List<Image>> {

    private NativeMapView nativeMapView;

    BitmapImageConversionTask(NativeMapView nativeMapView) {
      this.nativeMapView = nativeMapView;
    }

    @Override
    protected List<Image> doInBackground(HashMap<String, Bitmap>... params) {
      HashMap<String, Bitmap> bitmapHashMap = params[0];

      List<Image> images = new ArrayList<>();
      ByteBuffer buffer;
      String name;
      Bitmap bitmap;

      for (Map.Entry<String, Bitmap> stringBitmapEntry : bitmapHashMap.entrySet()) {
        name = stringBitmapEntry.getKey();
        bitmap = stringBitmapEntry.getValue();

        if (bitmap.getConfig() != Bitmap.Config.ARGB_8888) {
          bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, false);
        }

        buffer = ByteBuffer.allocate(bitmap.getByteCount());
        bitmap.copyPixelsToBuffer(buffer);

        float density = bitmap.getDensity() == Bitmap.DENSITY_NONE ? Bitmap.DENSITY_NONE : bitmap.getDensity();
        float pixelRatio = density / DisplayMetrics.DENSITY_DEFAULT;

        images.add(new Image(buffer.array(), pixelRatio, name, bitmap.getWidth(), bitmap.getHeight()));
      }

      return images;
    }

    @Override
    protected void onPostExecute(List<Image> images) {
      super.onPostExecute(images);
      if (nativeMapView != null && !nativeMapView.checkState("nativeAddImages")) {
        nativeMapView.nativeAddImages(images.toArray(new Image[images.size()]));
      }
    }
  }

  public interface ViewCallback {
    int getWidth();

    int getHeight();

    Bitmap getViewContent();
  }
}