summaryrefslogtreecommitdiff
path: root/android/java/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/views/MapView.java
blob: 217cc86b0702199095a1c175159c59b9ab3a121c (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
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
package com.mapbox.mapboxsdk.views;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Dialog;
import android.app.Fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.RectF;
import android.graphics.SurfaceTexture;
import android.graphics.drawable.BitmapDrawable;
import android.location.Location;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.FloatRange;
import android.support.annotation.IntRange;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.UiThread;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v4.view.ScaleGestureDetectorCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.InputDevice;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ZoomButtonsController;
import com.almeros.android.multitouch.gesturedetectors.RotateGestureDetector;
import com.almeros.android.multitouch.gesturedetectors.TwoFingerGestureDetector;
import com.mapbox.mapboxsdk.R;
import com.mapbox.mapboxsdk.annotations.Annotation;
import com.mapbox.mapboxsdk.annotations.Marker;
import com.mapbox.mapboxsdk.annotations.MarkerOptions;
import com.mapbox.mapboxsdk.annotations.Polygon;
import com.mapbox.mapboxsdk.annotations.PolygonOptions;
import com.mapbox.mapboxsdk.annotations.Polyline;
import com.mapbox.mapboxsdk.annotations.PolylineOptions;
import com.mapbox.mapboxsdk.geometry.BoundingBox;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.geometry.LatLngZoom;
import com.mapzen.android.lost.api.LocationListener;
import com.mapzen.android.lost.api.LocationRequest;
import com.mapzen.android.lost.api.LocationServices;
import com.mapzen.android.lost.api.LostApiClient;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 * A {@link MapView} provides an embeddable map interface, similar to the one provided by the Google Maps API.
 * You use this class to display map information and to manipulate the map contents from your application.
 * You can center the map on a given coordinate, specify the size of the area you want to display,
 * and style the features of the map to fit your application's use case.
 * <p/>
 * Use of {@link MapView} requires a Mapbox API access token.
 * Obtain an access token on the <a href="https://www.mapbox.com/account/apps/">Mapbox account page</a>.
 * <p/>
 * <strong>Warning:</strong> Please note that you are responsible for getting permission to use the map data,
 * and for ensuring your use adheres to the relevant terms of use.
 *
 * @see MapView#setAccessToken(String)
 */
public final class MapView extends FrameLayout implements LocationListener, CompassView.CompassDelegate {

    //
    // Static members
    //

    // Used for logging
    private static final String TAG = "MapView";

    // Used for animation
    private static final long ANIMATION_DURATION = 300;

    // Used for saving instance state
    private static final String STATE_CENTER_COORDINATE = "centerCoordinate";
    private static final String STATE_CENTER_DIRECTION = "centerDirection";
    private static final String STATE_ZOOM_LEVEL = "zoomLevel";
    private static final String STATE_DIRECTION = "direction";
    private static final String STATE_ZOOM_ENABLED = "zoomEnabled";
    private static final String STATE_SCROLL_ENABLED = "scrollEnabled";
    private static final String STATE_ROTATE_ENABLED = "rotateEnabled";
    private static final String STATE_DEBUG_ACTIVE = "debugActive";
    private static final String STATE_STYLE_URL = "styleUrl";
    private static final String STATE_ACCESS_TOKEN = "accessToken";
    private static final String STATE_STYLE_CLASSES = "styleClasses";
    private static final String STATE_DEFAULT_TRANSITION_DURATION = "defaultTransitionDuration";
    private static final String STATE_MY_LOCATION_ENABLED = "myLocationEnabled";
    private static final String STATE_COMPASS_ENABLED = "compassEnabled";
    private static final String STATE_COMPASS_GRAVITY = "compassGravity";
    private static final String STATE_COMPASS_MARGIN_LEFT = "compassMarginLeft";
    private static final String STATE_COMPASS_MARGIN_TOP = "compassMarginTop";
    private static final String STATE_COMPASS_MARGIN_RIGHT = "compassMarginRight";
    private static final String STATE_COMPASS_MARGIN_BOTTOM = "compassMarginBottom";
    private static final String STATE_LOGO_GRAVITY = "logoGravity";
    private static final String STATE_LOGO_MARGIN_LEFT = "logoMarginLeft";
    private static final String STATE_LOGO_MARGIN_TOP = "logoMarginTop";
    private static final String STATE_LOGO_MARGIN_RIGHT = "logoMarginRight";
    private static final String STATE_LOGO_MARGIN_BOTTOM = "logoMarginBottom";
    private static final String STATE_LOGO_VISIBILITY = "logoVisibility";
    private static final String STATE_ATTRIBUTION_GRAVITY = "attrGravity";
    private static final String STATE_ATTRIBUTION_MARGIN_LEFT = "attrMarginLeft";
    private static final String STATE_ATTRIBUTION_MARGIN_TOP = "attrMarginTop";
    private static final String STATE_ATTRIBUTION_MARGIN_RIGHT = "attrMarginRight";
    private static final String STATE_ATTRIBUTION_MARGIN_BOTTOM = "atrrMarginBottom";
    private static final String STATE_ATTRIBUTION_VISIBILITY = "atrrVisibility";

    // Used for positioning views
    private static final float DIMENSION_SEVEN_DP = 7f;
    private static final float DIMENSION_TEN_DP = 10f;
    private static final float DIMENSION_SIXTEEN_DP = 16f;
    private static final float DIMENSION_SEVENTYSIX_DP = 76f;

    // Used to select "Improve this map" link in the attribution dialog
    // Index into R.arrays.attribution_links
    private static final int ATTRIBUTION_INDEX_IMPROVE_THIS_MAP = 2;

    // Used for loading default marker sprite
    private static final String DEFAULT_SPRITE = "com.mapbox.sprites.default";

    /**
     * The currently supported maximum zoom level.
     *
     * @see MapView#setZoomLevel(double)
     */
    public static final double MAXIMUM_ZOOM_LEVEL = 18.0;

    //
    // Instance members
    //

    // Used to call JNI NativeMapView
    private NativeMapView mNativeMapView;

    // Used to track rendering
    private Boolean mDirty = false;

    // Used to handle DPI scaling
    private float mScreenDensity = 1.0f;
    private float mScreenDensityDpi = 1.0f;

    // Touch gesture detectors
    private GestureDetectorCompat mGestureDetector;
    private ScaleGestureDetector mScaleGestureDetector;
    private RotateGestureDetector mRotateGestureDetector;
    private boolean mTwoTap = false;

    // Shows zoom buttons
    private ZoomButtonsController mZoomButtonsController;

    // Used to track trackball long presses
    private TrackballLongPressTimeOut mCurrentTrackballLongPressTimeOut;

    // Receives changes to network connectivity
    private ConnectivityReceiver mConnectivityReceiver;

    // Holds the context
    private Context mContext;

    // Used for user location
    private LostApiClient mLocationClient;
    private LocationRequest mLocationRequest;
    private ImageView mGpsMarker;
    private Location mGpsLocation;

    // Used for the compass
    private CompassView mCompassView;

    // Used for displaying annotation markers
    // Every annotation that has been added to the map
    private final List<Annotation> mAnnotations = new ArrayList<>();
    private List<Annotation> mAnnotationsNearLastTap = new ArrayList<>();
    private Annotation mSelectedAnnotation;
    private InfoWindowAdapter mInfoWindowAdapter;

    // Used for the Mapbox Logo
    private ImageView mLogoView;

    // Used for attributions control
    private ImageView mAttributionsView;

    // Used to manage MapChange event listeners
    private ArrayList<OnMapChangedListener> mOnMapChangedListener;

    // Used to manage map click event listeners
    private OnMapClickListener mOnMapClickListener;
    private OnMapLongClickListener mOnMapLongClickListener;

    // Used to manage fling and scroll event listeners
    private OnFlingListener mOnFlingListener;
    private OnScrollListener mOnScrollListener;

    // Used to manage marker click event listeners
    private OnMarkerClickListener mOnMarkerClickListener;

    //
    // Properties
    //

    // These are properties with setters/getters, saved in onSaveInstanceState and XML attributes
    private boolean mZoomEnabled = true;
    private boolean mScrollEnabled = true;
    private boolean mRotateEnabled = true;
    private String mStyleUrl;
    private boolean mIsMyLocationEnabled = false;

    //
    // Inner classes
    //

    // These provide easy access to the bundled styles

    /**
     * StyleUrls provides URLs to several professional styles designed by Mapbox.
     * <p/>
     * These styles are all ready to go in your app. To load one, pass it into {@link MapView#setStyleUrl(String)}
     *
     * @see MapView#setStyleUrl(String)
     */
    public static final class StyleUrls {
        private StyleUrls() {
        }

        /**
         * Mapbox Streets: Our signature style.
         */
        public static final String MAPBOX_STREETS = "asset://styles/streets-v8.json";
        /**
         * Emerald: Great for transportation and outdoor terrain.
         */
        public static final String EMERALD = "asset://styles/emerald-v8.json";
        /**
         * Light: Light-colored style that is great for data overlay.
         */
        public static final String LIGHT = "asset://styles/light-v8.json";
        /**
         * Dark: Dark-colored style that is great for data overlay.
         */
        public static final String DARK = "asset://styles/dark-v8.json";
        /**
         * Satellite: The best-looking, most accurate, and most up-to-date satellite imagery available anywhere.
         */
        public static final String SATELLITE = "asset://styles/satellite-v8.json";
    }

    //
    // Enums
    //

    /**
     * Map change event types.
     *
     * @see MapView.OnMapChangedListener#onMapChanged(MapChange)
     */
    public enum MapChange {
        // TODO pull descriptions from C++
        RegionWillChange,
        RegionWillChangeAnimated,
        RegionIsChanging,
        RegionDidChange,
        RegionDidChangeAnimated,
        WillStartLoadingMap,
        DidFinishLoadingMap,
        DidFailLoadingMap,
        WillStartRenderingFrame,
        DidFinishRenderingFrame,
        DidFinishRenderingFrameFullyRendered,
        WillStartRenderingMap,
        DidFinishRenderingMap,
        DidFinishRenderingMapFullyRendered;

        // Converts the C++ values from include/mpbgl/map/view.hpp MapChange to Java enum values
        private static MapChange fromInteger(int value) {
            switch (value) {
                case 0:
                    return MapChange.RegionWillChange;
                case 1:
                    return MapChange.RegionWillChangeAnimated;
                case 2:
                    return MapChange.RegionIsChanging;
                case 3:
                    return MapChange.RegionDidChange;
                case 4:
                    return MapChange.RegionDidChangeAnimated;
                case 5:
                    return MapChange.WillStartLoadingMap;
                case 6:
                    return MapChange.DidFinishLoadingMap;
                case 7:
                    return MapChange.DidFailLoadingMap;
                case 8:
                    return MapChange.WillStartRenderingFrame;
                case 9:
                    return MapChange.DidFinishRenderingFrame;
                case 10:
                    return MapChange.DidFinishRenderingFrameFullyRendered;
                case 11:
                    return MapChange.WillStartRenderingMap;
                case 12:
                    return MapChange.DidFinishRenderingMap;
                case 13:
                    return MapChange.DidFinishRenderingMapFullyRendered;
                default:
                    return null;
            }
        }
    }

    //
    // Interfaces
    //

    /**
     * Interface definition for a callback to be invoked when the map is flinged.
     *
     * @see MapView#setOnFlingListener(OnFlingListener)
     */
    public interface OnFlingListener {
        /**
         * Called when the map is flinged.
         */
        void onFling();
    }

    /**
     * Interface definition for a callback to be invoked when the map is scrolled.
     *
     * @see MapView#setOnScrollListener(OnScrollListener)
     */
    public interface OnScrollListener {
        /**
         * Called when the map is scrolled.
         */
        void onScroll();
    }

    /**
     * Interface definition for a callback to be invoked on every frame rendered to the map view.
     *
     * @see MapView#setOnFpsChangedListener(OnFpsChangedListener)
     */
    public interface OnFpsChangedListener {
        /**
         * Called for every frame rendered to the map view.
         *
         * @param fps The average number of frames rendered over the last second.
         */
        void onFpsChanged(double fps);
    }

    /**
     * Interface definition for a callback to be invoked when the user clicks on the map view.
     *
     * @see MapView#setOnMapClickListener(OnMapClickListener)
     */
    public interface OnMapClickListener {
        /**
         * Called when the user clicks on the map view.
         *
         * @param point The projected map coordinate the user clicked on.
         */
        void onMapClick(LatLng point);
    }

    /**
     * Interface definition for a callback to be invoked when the user long clicks on the map view.
     *
     * @see MapView#setOnMapLongClickListener(OnMapLongClickListener)
     */
    public interface OnMapLongClickListener {
        /**
         * Called when the user long clicks on the map view.
         *
         * @param point The projected map coordinate the user long clicked on.
         */
        void onMapLongClick(LatLng point);
    }

    /**
     * Interface definition for a callback to be invoked when the user clicks on a marker.
     *
     * @see MapView#setOnMarkerClickListener(OnMarkerClickListener)
     */
    public interface OnMarkerClickListener {
        /**
         * Called when the user clicks on a marker.
         *
         * @param marker The marker the user clicked on.
         * @return If true the listener has consumed the event and the {@link InfoWindow} will not be shown.
         */
        boolean onMarkerClick(Marker marker);
    }

    /**
     * Interface definition for a callback to be invoked when the displayed map view changes.
     *
     * @see MapView#addOnMapChangedListener(OnMapChangedListener)
     * @see MapView.MapChange
     */
    public interface OnMapChangedListener {
        /**
         * Called when the displayed map view changes.
         *
         * @param change The type of map change event.
         */
        void onMapChanged(MapChange change);
    }

    /**
     * Interface definition for a callback to be invoked when an {@link InfoWindow} will be shown.
     *
     * @see MapView#setInfoWindowAdapter(InfoWindowAdapter)
     */
    public interface InfoWindowAdapter {
        /**
         * Called when an {@link InfoWindow} will be shown as a result of a marker click.
         *
         * @param marker The marker the user clicked on.
         * @return View to be shown as a {@link InfoWindow}.
         */
        View getInfoWindow(Marker marker);
    }

    //
    // Constructors
    //

    /**
     * Simple constructor to use when creating a {@link MapView} from code using the default map style.
     *
     * @param context     The {@link Context} of the {@link android.app.Activity}
     *                    or {@link android.app.Fragment} the {@link MapView} is running in.
     * @param accessToken Your public Mapbox access token. Used to load map styles and tiles.
     */
    @UiThread
    public MapView(@NonNull Context context, @NonNull String accessToken) {
        super(context);
        if (accessToken == null) {
            throw new NullPointerException("accessToken is null");
        }
        initialize(context, null);
        setAccessToken(accessToken);
        setStyleUrl(null);
    }

    /**
     * Simple constructor to use when creating a {@link MapView} from code using the provided map style URL.
     *
     * @param context     The {@link Context} of the {@link android.app.Activity}
     *                    or {@link android.app.Fragment} the {@link MapView} is running in.
     * @param accessToken Your public Mapbox access token. Used to load map styles and tiles.
     * @param styleUrl    A URL to the map style initially displayed. See {@link MapView#setStyleUrl(String)} for possible values.
     * @see MapView#setStyleUrl(String)
     */
    @UiThread
    public MapView(@NonNull Context context, @NonNull String accessToken, @NonNull String styleUrl) {
        super(context);
        if (accessToken == null) {
            throw new NullPointerException("accessToken is null");
        }
        if (styleUrl == null) {
            throw new NullPointerException("styleUrl is null");
        }
        initialize(context, null);
        setAccessToken(accessToken);
        setStyleUrl(styleUrl);
    }

    // Constructor that is called when inflating a view from XML.

    /**
     * Do not call from code.
     */
    @UiThread
    public MapView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initialize(context, attrs);
    }

    // Constructor that is called when inflating a view from XML.

    /**
     * Do not call from code.
     */
    @UiThread
    public MapView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initialize(context, attrs);
    }

    //
    // Initialization
    //

    // Common initialization code goes here
    private void initialize(Context context, AttributeSet attrs) {
        if (context == null) {
            throw new NullPointerException("context is null");
        }

        // Save the context
        mContext = context;

        // Create the TextureView
        TextureView textureView = new TextureView(mContext);
        addView(textureView);

        // Check if we are in Android Studio UI editor to avoid error in layout preview
        if (isInEditMode()) {
            return;
        }

        // Get the screen's density
        mScreenDensity = context.getResources().getDisplayMetrics().density;
        mScreenDensityDpi = context.getResources().getDisplayMetrics().densityDpi;

        // Get the cache path
        String cachePath = context.getCacheDir().getAbsolutePath();
        String dataPath = context.getFilesDir().getAbsolutePath();
        String apkPath = context.getPackageCodePath();

        // Create the NativeMapView
        int availableProcessors = Runtime.getRuntime().availableProcessors();
        ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        activityManager.getMemoryInfo(memoryInfo);
        long maxMemory = memoryInfo.availMem;
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            maxMemory = memoryInfo.totalMem;
        }
        mNativeMapView = new
                NativeMapView(this, cachePath, dataPath, apkPath, mScreenDensity, availableProcessors, maxMemory);

        // Ensure this view is interactable
        setClickable(true);
        setLongClickable(true);
        setFocusable(true);
        setFocusableInTouchMode(true);
        requestFocus();

        // Register the TextureView callbacks
        textureView.setSurfaceTextureListener(new SurfaceTextureListener());

        // Touch gesture detectors
        mGestureDetector = new GestureDetectorCompat(context, new GestureListener());
        mGestureDetector.setIsLongpressEnabled(true);
        mScaleGestureDetector = new ScaleGestureDetector(context, new ScaleGestureListener());
        ScaleGestureDetectorCompat.setQuickScaleEnabled(mScaleGestureDetector, true);
        mRotateGestureDetector = new RotateGestureDetector(context, new RotateGestureListener());

        // Shows the zoom controls
        // But not when in Eclipse UI editor
        if (!isInEditMode()) {
            if (!context.getPackageManager()
                    .hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH)) {
                mZoomButtonsController = new ZoomButtonsController(this);
                mZoomButtonsController.setZoomSpeed(ANIMATION_DURATION);
                mZoomButtonsController.setOnZoomListener(new OnZoomListener());
            }

            // Check current connection status
            ConnectivityManager connectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
            boolean isConnected = (activeNetwork != null) && activeNetwork.isConnectedOrConnecting();
            onConnectivityChanged(isConnected);
        }

        // Setup location aervices
        mLocationClient = new LostApiClient.Builder(getContext()).build();
        mLocationRequest = LocationRequest.create()
                .setInterval(1000)
                .setSmallestDisplacement(1)
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        // Setup user location UI
        mGpsMarker = new ImageView(getContext());
        mGpsMarker.setImageResource(R.drawable.location_marker);
        mGpsMarker.setVisibility(View.INVISIBLE);
        addView(mGpsMarker);

        // Setup compass
        mCompassView = new CompassView(mContext);
        mCompassView.setVisibility(View.INVISIBLE);
        mCompassView.setOnClickListener(new CompassView.CompassClickListener(this));
        addView(mCompassView);

        // Setup Mapbox logo
        mLogoView = new ImageView(mContext);
        mLogoView.setImageDrawable(ContextCompat.getDrawable(mContext, R.drawable.ic_logo_mapbox));
        mLogoView.setContentDescription(getResources().getString(R.string.mapboxIconContentDescription));
        LayoutParams logoParams = new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mLogoView.setLayoutParams(logoParams);
        addView(mLogoView);

        // Setup Attributions control
        mAttributionsView = new ImageView(mContext);
        mAttributionsView.setClickable(true);
        mAttributionsView.setImageResource(R.drawable.ic_info_selector);
        int attrPadding = (int) (DIMENSION_SEVEN_DP * mScreenDensity);
        mAttributionsView.setPadding(attrPadding, attrPadding, attrPadding, attrPadding);
        mAttributionsView.setAdjustViewBounds(true);
        mAttributionsView.setContentDescription(getResources()
                .getString(R.string.attributionsIconContentDescription));
        LayoutParams attrParams = new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mAttributionsView.setLayoutParams(attrParams);
        addView(mAttributionsView);
        mAttributionsView.setOnClickListener(new AttributionOnClickListener(this));

        // Setup Support For Listener Tracking
        // MapView's internal listener is setup in onCreate()
        mOnMapChangedListener = new ArrayList<>();

        // Load the attributes
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MapView, 0, 0);
        try {
            double centerLatitude = typedArray.getFloat(R.styleable.MapView_centerLatitude, 0.0f);
            double centerLongitude = typedArray.getFloat(R.styleable.MapView_centerLongitude, 0.0f);
            LatLng centerCoordinate = new LatLng(centerLatitude, centerLongitude);
            setCenterCoordinate(centerCoordinate);
            // need to set zoom level first because of limitation on rotating when zoomed out
            setZoomLevel(typedArray.getFloat(R.styleable.MapView_zoomLevel, 0.0f));
            setDirection(typedArray.getFloat(R.styleable.MapView_direction, 0.0f));
            setZoomEnabled(typedArray.getBoolean(R.styleable.MapView_zoomEnabled, true));
            setScrollEnabled(typedArray.getBoolean(R.styleable.MapView_scrollEnabled, true));
            setRotateEnabled(typedArray.getBoolean(R.styleable.MapView_rotateEnabled, true));
            setDebugActive(typedArray.getBoolean(R.styleable.MapView_debugActive, false));
            if (typedArray.getString(R.styleable.MapView_styleUrl) != null) {
                setStyleUrl(typedArray.getString(R.styleable.MapView_styleUrl));
            }
            if (typedArray.getString(R.styleable.MapView_accessToken) != null) {
                setAccessToken(typedArray.getString(R.styleable.MapView_accessToken));
            }
            if (typedArray.getString(R.styleable.MapView_styleClasses) != null) {
                List<String> styleClasses = Arrays.asList(typedArray
                        .getString(R.styleable.MapView_styleClasses).split("\\s*,\\s*"));
                for (String styleClass : styleClasses) {
                    if (styleClass.length() == 0) {
                        styleClasses.remove(styleClass);
                    }
                }
                setStyleClasses(styleClasses);
            }

            // Compass
            setCompassEnabled(typedArray.getBoolean(R.styleable.MapView_compassEnabled, true));
            setCompassGravity(typedArray.getInt(R.styleable.MapView_compassGravity, Gravity.TOP | Gravity.END));
            setWidgetMargins(mCompassView, typedArray.getDimension(R.styleable.MapView_compassMarginLeft, DIMENSION_TEN_DP)
                    , typedArray.getDimension(R.styleable.MapView_compassMarginTop, DIMENSION_TEN_DP)
                    , typedArray.getDimension(R.styleable.MapView_compassMarginRight, DIMENSION_TEN_DP)
                    , typedArray.getDimension(R.styleable.MapView_compassMarginBottom, DIMENSION_TEN_DP));

            // Logo
            setLogoVisibility(typedArray.getInt(R.styleable.MapView_logoVisibility, VISIBLE));
            setLogoGravity(typedArray.getInt(R.styleable.MapView_logoGravity, Gravity.BOTTOM | Gravity.START));
            setWidgetMargins(mLogoView, typedArray.getDimension(R.styleable.MapView_logoMarginLeft, DIMENSION_SIXTEEN_DP)
                    , typedArray.getDimension(R.styleable.MapView_logoMarginTop, DIMENSION_SIXTEEN_DP)
                    , typedArray.getDimension(R.styleable.MapView_logoMarginRight, DIMENSION_SIXTEEN_DP)
                    , typedArray.getDimension(R.styleable.MapView_logoMarginBottom, DIMENSION_SIXTEEN_DP));

            // Attribution
            setAttributionVisibility(typedArray.getInt(R.styleable.MapView_attributionVisibility, VISIBLE));
            setAttributionGravity(typedArray.getInt(R.styleable.MapView_attributionGravity, Gravity.BOTTOM));
            setWidgetMargins(mAttributionsView, typedArray.getDimension(R.styleable.MapView_attributionMarginLeft, DIMENSION_SEVENTYSIX_DP)
                    , typedArray.getDimension(R.styleable.MapView_attributionMarginTop, DIMENSION_SEVEN_DP)
                    , typedArray.getDimension(R.styleable.MapView_attributionMarginRight, DIMENSION_SEVEN_DP)
                    , typedArray.getDimension(R.styleable.MapView_attributionMarginBottom, DIMENSION_SEVEN_DP));

            // User location
            setMyLocationEnabled(typedArray.getBoolean(R.styleable.MapView_myLocationEnabled, false));
        } finally {
            typedArray.recycle();
        }
    }

    //
    // Lifecycle events
    //

    /**
     * You must call this method from the parent's {@link android.app.Activity#onCreate(Bundle)} or
     * {@link android.app.Fragment#onCreate(Bundle)}.
     * </p>
     * You must set a valid access token with {@link MapView#setAccessToken(String)} before you this method
     * or an exception will be thrown.
     *
     * @param savedInstanceState Pass in the parent's savedInstanceState.
     * @see MapView#setAccessToken(String)
     */
    @UiThread
    public void onCreate(@Nullable Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            setCenterCoordinate((LatLng) savedInstanceState.getParcelable(STATE_CENTER_COORDINATE));
            // need to set zoom level first because of limitation on rotating when zoomed out
            setZoomLevel(savedInstanceState.getDouble(STATE_ZOOM_LEVEL));
            setDirection(savedInstanceState.getDouble(STATE_CENTER_DIRECTION));
            setDirection(savedInstanceState.getDouble(STATE_DIRECTION));
            setZoomEnabled(savedInstanceState.getBoolean(STATE_ZOOM_ENABLED));
            setScrollEnabled(savedInstanceState.getBoolean(STATE_SCROLL_ENABLED));
            setRotateEnabled(savedInstanceState.getBoolean(STATE_ROTATE_ENABLED));
            setDebugActive(savedInstanceState.getBoolean(STATE_DEBUG_ACTIVE));
            setStyleUrl(savedInstanceState.getString(STATE_STYLE_URL));
            setAccessToken(savedInstanceState.getString(STATE_ACCESS_TOKEN));
            List<String> appliedStyleClasses = savedInstanceState.getStringArrayList(STATE_STYLE_CLASSES);
            if (!appliedStyleClasses.isEmpty()) {
                setStyleClasses(appliedStyleClasses);
            }
            mNativeMapView.setDefaultTransitionDuration(
                    savedInstanceState.getLong(STATE_DEFAULT_TRANSITION_DURATION));
            setMyLocationEnabled(savedInstanceState.getBoolean(STATE_MY_LOCATION_ENABLED));

            // Compass
            setCompassEnabled(savedInstanceState.getBoolean(STATE_COMPASS_ENABLED));
            setCompassGravity(savedInstanceState.getInt(STATE_COMPASS_GRAVITY));
            setCompassMargins(savedInstanceState.getInt(STATE_COMPASS_MARGIN_LEFT)
                    , savedInstanceState.getInt(STATE_COMPASS_MARGIN_TOP)
                    , savedInstanceState.getInt(STATE_COMPASS_MARGIN_RIGHT)
                    , savedInstanceState.getInt(STATE_COMPASS_MARGIN_BOTTOM));

            // Logo
            setLogoVisibility(savedInstanceState.getInt(STATE_LOGO_VISIBILITY));
            setLogoGravity(savedInstanceState.getInt(STATE_LOGO_GRAVITY));
            setLogoMargins(savedInstanceState.getInt(STATE_LOGO_MARGIN_LEFT)
                    , savedInstanceState.getInt(STATE_LOGO_MARGIN_TOP)
                    , savedInstanceState.getInt(STATE_LOGO_MARGIN_RIGHT)
                    , savedInstanceState.getInt(STATE_LOGO_MARGIN_BOTTOM));

            // Attribution
            setAttributionVisibility(savedInstanceState.getInt(STATE_ATTRIBUTION_VISIBILITY));
            setAttributionGravity(savedInstanceState.getInt(STATE_ATTRIBUTION_GRAVITY));
            setAttributionMargins(savedInstanceState.getInt(STATE_ATTRIBUTION_MARGIN_LEFT)
                    , savedInstanceState.getInt(STATE_ATTRIBUTION_MARGIN_TOP)
                    , savedInstanceState.getInt(STATE_ATTRIBUTION_MARGIN_RIGHT)
                    , savedInstanceState.getInt(STATE_ATTRIBUTION_MARGIN_BOTTOM));
        }

        // Force a check for an access token
        validateAccessToken(getAccessToken());

        // Initialize EGL
        mNativeMapView.initializeDisplay();
        mNativeMapView.initializeContext();

        // Add annotation deselection listener
        addOnMapChangedListener(new OnMapChangedListener() {
            @Override
            public void onMapChanged(MapChange change) {
                if (change.equals(MapChange.RegionWillChange) ||
                        change.equals(MapChange.RegionWillChangeAnimated)) {
                    deselectAnnotation();
                }
            }
        });
    }

    /**
     * You must call this method from the parent's {@link android.app.Activity#onSaveInstanceState(Bundle)}
     * or {@link android.app.Fragment#onSaveInstanceState(Bundle)}.
     *
     * @param outState Pass in the parent's outState.
     */
    @UiThread
    public void onSaveInstanceState(@NonNull Bundle outState) {
        if (outState == null) {
            throw new NullPointerException("outState is null");
        }

        outState.putParcelable(STATE_CENTER_COORDINATE, getCenterCoordinate());
        // need to set zoom level first because of limitation on rotating when zoomed out
        outState.putDouble(STATE_ZOOM_LEVEL, getZoomLevel());
        outState.putDouble(STATE_CENTER_DIRECTION, getDirection());
        outState.putBoolean(STATE_ZOOM_ENABLED, mZoomEnabled);
        outState.putBoolean(STATE_SCROLL_ENABLED, mScrollEnabled);
        outState.putBoolean(STATE_ROTATE_ENABLED, mRotateEnabled);
        outState.putBoolean(STATE_DEBUG_ACTIVE, isDebugActive());
        outState.putString(STATE_STYLE_URL, mStyleUrl);
        outState.putString(STATE_ACCESS_TOKEN, getAccessToken());
        outState.putStringArrayList(STATE_STYLE_CLASSES, new ArrayList<>(getStyleClasses()));
        outState.putLong(STATE_DEFAULT_TRANSITION_DURATION, mNativeMapView.getDefaultTransitionDuration());
        outState.putBoolean(STATE_MY_LOCATION_ENABLED, isMyLocationEnabled());

        // Compass
        LayoutParams compassParams = (LayoutParams) mCompassView.getLayoutParams();
        outState.putBoolean(STATE_COMPASS_ENABLED, isCompassEnabled());
        outState.putInt(STATE_COMPASS_GRAVITY, compassParams.gravity);
        outState.putInt(STATE_COMPASS_MARGIN_LEFT, compassParams.leftMargin);
        outState.putInt(STATE_COMPASS_MARGIN_TOP, compassParams.topMargin);
        outState.putInt(STATE_COMPASS_MARGIN_BOTTOM, compassParams.bottomMargin);
        outState.putInt(STATE_COMPASS_MARGIN_RIGHT, compassParams.rightMargin);

        // Logo
        LayoutParams logoParams = (LayoutParams) mLogoView.getLayoutParams();
        outState.putInt(STATE_LOGO_GRAVITY, logoParams.gravity);
        outState.putInt(STATE_LOGO_MARGIN_LEFT, logoParams.leftMargin);
        outState.putInt(STATE_LOGO_MARGIN_TOP, logoParams.topMargin);
        outState.putInt(STATE_LOGO_MARGIN_RIGHT, logoParams.rightMargin);
        outState.putInt(STATE_LOGO_MARGIN_BOTTOM, logoParams.bottomMargin);
        outState.putInt(STATE_LOGO_VISIBILITY, mLogoView.getVisibility());

        // Attribution
        LayoutParams attrParams = (LayoutParams) mAttributionsView.getLayoutParams();
        outState.putInt(STATE_ATTRIBUTION_GRAVITY, attrParams.gravity);
        outState.putInt(STATE_ATTRIBUTION_MARGIN_LEFT, attrParams.leftMargin);
        outState.putInt(STATE_ATTRIBUTION_MARGIN_TOP, attrParams.topMargin);
        outState.putInt(STATE_ATTRIBUTION_MARGIN_RIGHT, attrParams.rightMargin);
        outState.putInt(STATE_ATTRIBUTION_MARGIN_BOTTOM, attrParams.bottomMargin);
        outState.putInt(STATE_ATTRIBUTION_VISIBILITY, mAttributionsView.getVisibility());
    }

    /**
     * You must call this method from the parent's {@link Activity#onDestroy()} or {@link Fragment#onDestroy()}.
     */
    @UiThread
    public void onDestroy() {
        mNativeMapView.terminateContext();
        mNativeMapView.terminateDisplay();
    }

    /**
     * You must call this method from the parent's {@link Activity#onStart()} or {@link Fragment#onStart()}.
     */
    @UiThread
    public void onStart() {
    }

    /**
     * You must call this method from the parent's {@link Activity#onStop()} or {@link Fragment#onStop()}
     */
    @UiThread
    public void onStop() {
    }

    /**
     * You must call this method from the parent's {@link Activity#onPause()} or {@link Fragment#onPause()}.
     */
    @UiThread
    public void onPause() {
        // Register for connectivity changes
        getContext().unregisterReceiver(mConnectivityReceiver);
        mConnectivityReceiver = null;

        if (mIsMyLocationEnabled) {
            toggleGps(false);
        }

        mNativeMapView.pause();
    }

    /**
     * You must call this method from the parent's {@link Activity#onResume()} or {@link Fragment#onResume()}.
     */
    @UiThread
    public void onResume() {
        // Register for connectivity changes
        mConnectivityReceiver = new ConnectivityReceiver();
        mContext.registerReceiver(mConnectivityReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

        if (mIsMyLocationEnabled) {
            toggleGps(true);
        }

        mNativeMapView.resume();
    }

    /**
     * You must call this method from the parent's {@link Activity#onLowMemory()} or {@link Fragment#onLowMemory()}.
     */
    @UiThread
    public void onLowMemory() {
        mNativeMapView.onLowMemory();
    }

    //
    // Position
    //

    /**
     * Returns the current coordinate at the center of the map view.
     *
     * @return The current coordinate.
     */
    @UiThread
    @NonNull
    public LatLng getCenterCoordinate() {
        return mNativeMapView.getLatLng();
    }

    /**
     * Centers the map on a new coordinate immediately without changing the zoom level.
     * <p/>
     * The initial coordinate is (0, 0).
     * <p/>
     * If you want to animate the change, use {@link MapView#setCenterCoordinate(LatLng, boolean)}.
     *
     * @param centerCoordinate The new coordinate.
     * @see MapView#setCenterCoordinate(LatLng, boolean)
     */
    @UiThread
    public void setCenterCoordinate(@NonNull LatLng centerCoordinate) {
        setCenterCoordinate(centerCoordinate, false);
    }

    /**
     * Centers the map on a new coordinate without changing the zoom level and optionally animates the change.
     * <p/>
     * The initial coordinate is (0, 0).
     *
     * @param centerCoordinate The new coordinate.
     * @param animated         If true, animates the change. If false, immediately changes the map.
     */
    @UiThread
    public void setCenterCoordinate(@NonNull LatLng centerCoordinate, boolean animated) {
        if (centerCoordinate == null) {
            throw new NullPointerException("centerCoordinate is null");
        }
        long duration = animated ? ANIMATION_DURATION : 0;
        mNativeMapView.cancelTransitions();
        mNativeMapView.setLatLng(centerCoordinate, duration);
    }


    /**
     * Centers the map on a new coordinate immediately while changing the current zoom level.
     * <p/>
     * The initial value is a center coordinate of (0, 0) and a zoom level of 0.
     * <p/>
     * If you want to animate the change, use {@link MapView#setCenterCoordinate(LatLngZoom, boolean)}.
     *
     * @param centerCoordinate The new coordinate and zoom level.
     * @see MapView#setCenterCoordinate(LatLngZoom, boolean)
     */
    @UiThread
    public void setCenterCoordinate(@NonNull LatLngZoom centerCoordinate) {
        setCenterCoordinate(centerCoordinate, false);
    }

    /**
     * Resets the map to the minimum zoom level, a center coordinate of (0, 0), a true north heading,
     * and animates the change.
     */
    @UiThread
    public void resetPosition() {
        mNativeMapView.cancelTransitions();
        mNativeMapView.resetPosition();
    }

    /**
     * Centers the map on a new coordinate while changing the zoom level and optionally animates the change.
     * <p/>
     * The initial value is a center coordinate of (0, 0) and a zoom level of 0.
     *
     * @param centerCoordinate The new coordinate and zoom level.
     * @param animated         If true, animates the change. If false, immediately changes the map.
     */
    @UiThread
    public void setCenterCoordinate(@NonNull LatLngZoom centerCoordinate,
                                    boolean animated) {
        if (centerCoordinate == null) {
            throw new NullPointerException("centerCoordinate is null");
        }
        long duration = animated ? ANIMATION_DURATION : 0;
        mNativeMapView.cancelTransitions();
        mNativeMapView.setLatLngZoom(centerCoordinate, duration);
    }

    /**
     * Returns whether the user may scroll around the map.
     *
     * @return If true, scrolling is enabled.
     */
    @UiThread
    public boolean isScrollEnabled() {
        return mScrollEnabled;
    }

    /**
     * Changes whether the user may scroll around the map.
     * <p/>
     * This setting controls only user interactions with the map. If you set the value to false,
     * you may still change the map location programmatically.
     * <p/>
     * The default value is true.
     *
     * @param scrollEnabled If true, scrolling is enabled.
     */
    @UiThread
    public void setScrollEnabled(boolean scrollEnabled) {
        this.mScrollEnabled = scrollEnabled;
    }

    //
    // Rotation
    //

    /**
     * Returns the current heading of the map relative to true north.
     *
     * @return The current heading measured in degrees.
     */
    @UiThread
    @FloatRange(from = 0, to = 360)
    public double getDirection() {
        double direction = -mNativeMapView.getBearing();

        while (direction > 360) {
            direction -= 360;
        }
        while (direction < 0) {
            direction += 360;
        }

        return direction;
    }

    /**
     * Rotates the map to a new heading relative to true north immediately.
     * <p/>
     * The value 0 means that the top edge of the map view will correspond to true north.<br>
     * The value 90 means the top of the map will point due east.<br>
     * The value 180 means the top of the map will point due south.<br>
     * The value 270 means the top of the map will point due west.
     * <p/>
     * The initial heading is 0.
     * <p/>
     * If you want to animate the change, use {@link MapView#setDirection(double, boolean)}.
     *
     * @param direction The new heading measured in degrees.
     * @see MapView#setDirection(double, boolean)
     */
    @UiThread
    public void setDirection(@FloatRange(from = 0, to = 360) double direction) {
        setDirection(direction, false);
    }

    /**
     * Rotates the map to a new heading relative to true north and optionally animates the change.
     * <p/>
     * The value 0 means that the top edge of the map view will correspond to true north.<br/>
     * The value 90 means the top of the map will point due east.<br/>
     * The value 180 means the top of the map will point due south.<br/>
     * The value 270 means the top of the map will point due west
     * <p/>
     * The initial heading is 0.
     *
     * @param direction The new heading measured in degrees from true north.
     * @param animated  If true, animates the change. If false, immediately changes the map.
     */
    @UiThread
    public void setDirection(@FloatRange(from = 0, to = 360) double direction, boolean animated) {
        long duration = animated ? ANIMATION_DURATION : 0;
        mNativeMapView.cancelTransitions();
        // Out of range direactions are normallised in setBearing
        mNativeMapView.setBearing(-direction, duration);
    }

    /**
     * Resets the map heading to true north and animates the change.
     */
    @UiThread
    public void resetNorth() {
        mNativeMapView.cancelTransitions();
        mNativeMapView.resetNorth();
    }

    /**
     * Returns whether the user may rotate the map.
     *
     * @return If true, rotating is enabled.
     */
    @UiThread
    public boolean isRotateEnabled() {
        return mRotateEnabled;
    }

    /**
     * Changes whether the user may rotate the map.
     * <p/>
     * This setting controls only user interactions with the map. If you set the value to false,
     * you may still change the map location programmatically.
     * <p/>
     * The default value is true.
     *
     * @param rotateEnabled If true, rotating is enabled.
     */
    @UiThread
    public void setRotateEnabled(boolean rotateEnabled) {
        this.mRotateEnabled = rotateEnabled;
    }

    //
    // Scale
    //

    /**
     * Returns the current zoom level of the map view.
     *
     * @return The current zoom level.
     */
    @UiThread
    @FloatRange(from = 0.0, to = MAXIMUM_ZOOM_LEVEL)
    public double getZoomLevel() {
        return mNativeMapView.getZoom();
    }

    /**
     * Zooms the map to a new zoom level immediately without changing the center coordinate.
     * <p/>
     * At zoom level 0, tiles cover the entire world map;
     * at zoom level 1, tiles cover &frac14 of the world;
     * at zoom level 2, tiles cover 1/16 of the world, and so on.
     * <p/>
     * The initial zoom level is 0. The maximum zoom level is {@link MapView#MAXIMUM_ZOOM_LEVEL}.
     * <p/>
     * If you want to animate the change, use {@link MapView#setZoomLevel(double, boolean)}.
     *
     * @param zoomLevel The new coordinate.
     * @see MapView#setZoomLevel(double, boolean)
     * @see MapView#MAXIMUM_ZOOM_LEVEL
     */
    @UiThread
    public void setZoomLevel(@FloatRange(from = 0.0, to = MAXIMUM_ZOOM_LEVEL) double zoomLevel) {
        setZoomLevel(zoomLevel, false);
    }

    /**
     * Zooms the map to a new zoom level and optionally animates the change without changing the center coordinate.
     * <p/>
     * At zoom level 0, tiles cover the entire world map;
     * at zoom level 1, tiles cover &frac14 of the world;
     * at zoom level 2, tiles cover 1/16 of the world, and so on.
     * <p/>
     * The initial zoom level is 0. The maximum zoom level is {@link MapView#MAXIMUM_ZOOM_LEVEL}.
     *
     * @param zoomLevel The new coordinate.
     * @param animated  If true, animates the change. If false, immediately changes the map.
     * @see MapView#MAXIMUM_ZOOM_LEVEL
     */
    @UiThread
    public void setZoomLevel(@FloatRange(from = 0.0, to = MAXIMUM_ZOOM_LEVEL) double zoomLevel, boolean animated) {
        if ((zoomLevel < 0.0) || (zoomLevel > MAXIMUM_ZOOM_LEVEL)) {
            throw new IllegalArgumentException("zoomLevel is < 0 or > MapView.MAXIMUM_ZOOM_LEVEL");
        }
        long duration = animated ? ANIMATION_DURATION : 0;
        mNativeMapView.cancelTransitions();
        mNativeMapView.setZoom(zoomLevel, duration);
    }

    /**
     * Returns whether the user may zoom the map.
     *
     * @return If true, zooming is enabled.
     */
    @UiThread
    public boolean isZoomEnabled() {
        return mZoomEnabled;
    }

    /**
     * Changes whether the user may zoom the map.
     * <p/>
     * This setting controls only user interactions with the map. If you set the value to false,
     * you may still change the map location programmatically.
     * <p/>
     * The default value is true.
     *
     * @param zoomEnabled If true, zooming is enabled.
     */
    @UiThread
    public void setZoomEnabled(boolean zoomEnabled) {
        this.mZoomEnabled = zoomEnabled;

        if ((mZoomButtonsController != null) && (getVisibility() == View.VISIBLE) && mZoomEnabled) {
            mZoomButtonsController.setVisible(true);
        }
    }

    // Zoom in or out
    private void zoom(boolean zoomIn) {
        zoom(zoomIn, -1.0f, -1.0f);
    }

    private void zoom(boolean zoomIn, float x, float y) {
        // Cancel any animation
        mNativeMapView.cancelTransitions();

        if (zoomIn) {
            mNativeMapView.scaleBy(2.0, x / mScreenDensity, y / mScreenDensity, ANIMATION_DURATION);
        } else {
            mNativeMapView.scaleBy(0.5, x / mScreenDensity, y / mScreenDensity, ANIMATION_DURATION);
        }
    }

    //
    // Debug
    //

    /**
     * Returns whether the map debug information is currently shown.
     *
     * @return If true, map debug information is currently shown.
     */
    @UiThread
    public boolean isDebugActive() {
        return mNativeMapView.getDebug() || mNativeMapView.getCollisionDebug();
    }

    /**
     * Changes whether the map debug information is shown.
     * <p/>
     * The default value is false.
     *
     * @param debugActive If true, map debug information is shown.
     */
    @UiThread
    public void setDebugActive(boolean debugActive) {
        mNativeMapView.setDebug(debugActive);
        mNativeMapView.setCollisionDebug(debugActive);
    }

    /**
     * Toggles whether the map debug information is shown.
     * <p/>
     * The value of {@link MapView#isDebugActive()} is toggled.
     *
     * @see MapView#isDebugActive()
     */
    @UiThread
    public void toggleDebug() {
        mNativeMapView.toggleDebug();
        mNativeMapView.toggleCollisionDebug();
    }

    // True if map has finished loading the view
    private boolean isFullyLoaded() {
        return mNativeMapView.isFullyLoaded();
    }

    //
    // Styling
    //

    /**
     * Loads a new map style from the specified URL.
     * <p/>
     * {@code url} can take the following forms:
     * <ul>
     * <li>{@code MapView.StyleUrls.*}: load one of the bundled styles in {@link MapView.StyleUrls}.</li>
     * <li>{@code mapbox://styles/<user>/<style>}:
     * retrieves the style from a <a href="https://www.mapbox.com/account/">Mapbox account.</a>
     * {@code user} is your username. {@code style} is the ID of your custom
     * style created in <a href="https://www.mapbox.com/studio">Mapbox Studio</a>.</li>
     * <li>{@code http://...} or {@code https://...}:
     * retrieves the style over the Internet from any web server.</li>
     * <li>{@code asset://...}:
     * reads the style from the APK {@code asset/} directory.
     * This is used to load a style bundled with your app.</li>
     * <li>{@code null}: loads the default {@link MapView.StyleUrls#MAPBOX_STREETS} style.</li>
     * </ul>
     * <p/>
     * This method is asynchronous and will return immediately before the style finishes loading.
     * If you wish to wait for the map to finish loading listen for the {@link MapView.MapChange#DidFinishLoadingMap} event.
     * <p/>
     * If the style fails to load or an invalid style URL is set, the map view will become blank.
     * An error message will be logged in the Android logcat and {@link MapView.MapChange#DidFailLoadingMap} event will be sent.
     *
     * @param url The URL of the map style
     * @see MapView.StyleUrls
     */
    @UiThread
    public void setStyleUrl(@Nullable String url) {
        if (url == null) {
            url = StyleUrls.MAPBOX_STREETS;
        }
        mStyleUrl = url;
        mNativeMapView.setStyleUrl(url);
    }

    /**
     * Returns the map style currently displayed in the map view.
     * <p/>
     * If the default style is currently displayed, a URL will be returned instead of null.
     *
     * @return The URL of the map style.
     */
    @UiThread
    @NonNull
    public String getStyleUrl() {
        return mStyleUrl;
    }

    /**
     * Returns the set of currently active map style classes.
     *
     * @return A list of class identifiers.
     */
    @UiThread
    @NonNull
    public List<String> getStyleClasses() {
        return Collections.unmodifiableList(mNativeMapView.getClasses());
    }

    /**
     * Changes the set of currently active map style classes immediately.
     * <p/>
     * The list of valid class identifiers is defined by the currently loaded map style.
     * <p/>
     * If you want to animate the change, use {@link MapView#setStyleClasses(List, long)}.
     *
     * @param styleClasses A list of class identifiers.
     * @see MapView#setStyleClasses(List, long)
     * @see MapView#setStyleUrl(String)
     */
    @UiThread
    public void setStyleClasses(@NonNull List<String> styleClasses) {
        setStyleClasses(styleClasses, 0);
    }

    /**
     * Changes the set of currently active map style classes with an animated transition.
     * <p/>
     * The list of valid class identifiers is defined by the currently loaded map style.
     *
     * @param styleClasses       A list of class identifiers.
     * @param transitionDuration The duration of the transition animation in milliseconds.
     * @see MapView#setStyleClasses(List, long)
     * @see MapView#setStyleUrl(String)
     */
    @UiThread
    public void setStyleClasses(@NonNull List<String> styleClasses, @IntRange(from = 0) long transitionDuration) {
        if (styleClasses == null) {
            throw new NullPointerException("styleClasses is null");
        }
        if (transitionDuration < 0) {
            throw new IllegalArgumentException("transitionDuration is < 0");
        }
        // TODO non negative check and annotation (go back and check other functions too)
        mNativeMapView.setDefaultTransitionDuration(transitionDuration);
        mNativeMapView.setClasses(styleClasses);
    }

    /**
     * Activates the specified map style class.
     * <p/>
     * If you want to animate the change, use {@link MapView#setStyleClasses(List, long)}.
     *
     * @param styleClass The class identifier.
     * @see MapView#setStyleClasses(List, long)
     */
    @UiThread
    public void addStyleClass(@NonNull String styleClass) {
        if (styleClass == null) {
            throw new NullPointerException("styleClass is null");
        }
        mNativeMapView.addClass(styleClass);
    }

    /**
     * Deactivates the specified map style class.
     * <p/>
     * If you want to animate the change, use {@link MapView#setStyleClasses(List, long)}.
     *
     * @param styleClass The class identifier.
     * @see MapView#setStyleClasses(List, long)
     */
    @UiThread
    public void removeStyleClass(@NonNull String styleClass) {
        if (styleClass == null) {
            throw new NullPointerException("styleClass is null");
        }
        mNativeMapView.removeClass(styleClass);
    }

    /**
     * Returns whether the specified map style class is currently active.
     *
     * @param styleClass The class identifier.
     * @return If true, the class is currently active.
     */
    @UiThread
    public boolean hasStyleClass(@NonNull String styleClass) {
        if (styleClass == null) {
            throw new NullPointerException("styleClass is null");
        }
        return mNativeMapView.hasClass(styleClass);
    }

    /**
     * Deactivates all the currently active map style classes immediately.
     * <p/>
     * If you want to animate the change, use {@link MapView#removeAllStyleClasses(long)}.
     *
     * @see MapView#removeAllStyleClasses(long)
     */
    @UiThread
    public void removeAllStyleClasses() {
        removeAllStyleClasses(0);
    }

    /**
     * Deactivates all the currently active map style classes with an animated transition.
     *
     * @param transitionDuration The duration of the transition animation in milliseconds.
     */
    @UiThread
    public void removeAllStyleClasses(@IntRange(from = 0) long transitionDuration) {
        if (transitionDuration < 0) {
            throw new IllegalArgumentException("transitionDuration is < 0");
        }
        mNativeMapView.setDefaultTransitionDuration(transitionDuration);
        ArrayList<String> styleClasses = new ArrayList<>(0);
        setStyleClasses(styleClasses);
    }

    //
    // Access token
    //

    // Checks if the given token is valid
    private void validateAccessToken(String accessToken) {
        if (TextUtils.isEmpty(accessToken) || (!accessToken.startsWith("pk.") && !accessToken.startsWith("sk."))) {
            throw new RuntimeException("Using MapView requires setting a valid access token. See the README.md");
        }
    }

    /**
     * Sets the current Mapbox access token used to load map styles and tiles.
     * <p/>
     * You must set a valid access token before you call {@link MapView#onCreate(Bundle)}
     * or an exception will be thrown.
     *
     * @param accessToken Your public Mapbox access token.
     * @see MapView#onCreate(Bundle)
     */
    @UiThread
    public void setAccessToken(@NonNull String accessToken) {
        // validateAccessToken does the null check
        validateAccessToken(accessToken);
        mNativeMapView.setAccessToken(accessToken);
    }

    /**
     * Returns the current Mapbox access token used to load map styles and tiles.
     *
     * @return The current Mapbox access token.
     */
    @UiThread
    @Nullable
    public String getAccessToken() {
        return mNativeMapView.getAccessToken();
    }

    //
    // Projection
    //

    /**
     * Converts a point in this view's coordinate system to a map coordinate.
     *
     * @param point A point in this view's coordinate system.
     * @return The converted map coordinate.
     */
    @UiThread
    @NonNull
    public LatLng fromScreenLocation(@NonNull PointF point) {
        if (point == null) {
            throw new NullPointerException("point is null");
        }

        float x = point.x;
        float y = point.y;

        // flip y direction vertically to match core GL
        y = getHeight() - y;

        return mNativeMapView.latLngForPixel(new PointF(x / mScreenDensity, y / mScreenDensity));
    }

    /**
     * Converts a map coordinate to a point in this view's coordinate system.
     *
     * @param location A map coordinate.
     * @return The converted point in this view's coordinate system.
     */
    @UiThread
    @NonNull
    public PointF toScreenLocation(@NonNull LatLng location) {
        if (location == null) {
            throw new NullPointerException("location is null");
        }

        PointF point = mNativeMapView.pixelForLatLng(location);

        float x = point.x * mScreenDensity;
        float y = point.y * mScreenDensity;

        // flip y direction vertically to match core GL
        y = getHeight() - y;

        return new PointF(x, y);
    }

    //
    // Annotations
    //

    // Marking this function private until #2506 fixed
    private void setSprite(String symbol, Bitmap bitmap) {
        if (bitmap.getConfig() != Bitmap.Config.ARGB_8888) {
            bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, false);
        }
        ByteBuffer buffer = ByteBuffer.allocate(bitmap.getRowBytes() * bitmap.getHeight());
        bitmap.copyPixelsToBuffer(buffer);

        //float scale = mScreenDensityDpi / bitmap.getDensity() * mScreenDensity;
        float scale = 1.0f;

        mNativeMapView.setSprite(symbol, bitmap.getWidth(), bitmap.getHeight(), scale, buffer.array());
    }

    public Marker addMarker(MarkerOptions markerOptions) {
        Marker marker = markerOptions.getMarker();

        // Load the default marker sprite
        if (marker.getSprite() == null) {
            BitmapDrawable bitmapDrawable = (BitmapDrawable) ContextCompat.getDrawable(mContext, R.drawable.default_marker);
            Bitmap bitmap = bitmapDrawable.getBitmap();
            setSprite(DEFAULT_SPRITE, bitmap);

            // Red default marker is currently broken
            marker.setSprite("default_marker");
            //marker.setSprite(DEFAULT_SPRITE);
        }

        long id = mNativeMapView.addMarker(marker);
        marker.setId(id);        // the annotation needs to know its id
        marker.setMapView(this); // the annotation needs to know which map view it is in
        mAnnotations.add(marker);
        return marker;
    }

    public List<Marker> addMarkers(List<Marker> markers) {
        long[] ids = mNativeMapView.addMarkers(markers);
        Marker m;
        int count = markers.size();
        for (int i = 0; i < count; i++) {
            m = markers.get(i);
            m.setId(ids[i]);
            m.setMapView(this);
            mAnnotations.add(m);
        }
        return markers;
    }

    public Polyline addPolyline(PolylineOptions polylineOptions) {
        Polyline polyline = polylineOptions.getPolyline();
        long id = mNativeMapView.addPolyline(polyline);
        polyline.setId(id);
        polyline.setMapView(this);
        mAnnotations.add(polyline);
        return polyline;
    }

    public Polygon addPolygon(PolygonOptions polygonOptions) {
        Polygon polygon = polygonOptions.getPolygon();
        long id = mNativeMapView.addPolygon(polygon);
        polygon.setId(id);
        polygon.setMapView(this);
        mAnnotations.add(polygon);
        return polygon;
    }

    public List<Polygon> addPolygons(List<PolygonOptions> polygonOptions) {
        List<Polygon> polygons = new ArrayList<>();
        for (PolygonOptions popts : polygonOptions) {
            polygons.add(popts.getPolygon());
        }

        long[] ids = mNativeMapView.addPolygons(polygons);

        for (int i = 0; i < polygons.size(); i++) {
            polygons.get(i).setId(ids[i]);
            polygons.get(i).setMapView(this);
            mAnnotations.add(polygons.get(i));
        }

        return Collections.unmodifiableList(polygons);
    }

    private void removeAnnotationsWithId(long annotationId) {
        for (Iterator<Annotation> iterator = mAnnotations.iterator(); iterator.hasNext(); ) {
            Annotation annotation = iterator.next();
            if (annotation instanceof Marker) {
                ((Marker) annotation).hideInfoWindow();
            }
            if (annotation.getId() == annotationId) {
                iterator.remove();
            }
        }
    }

    public void removeAnnotation(Annotation annotation) {
        if (annotation instanceof Marker) {
            ((Marker) annotation).hideInfoWindow();
        }
        long id = annotation.getId();
        mNativeMapView.removeAnnotation(id);
        mAnnotations.remove(annotation);
    }

    public void removeAnnotation(long annotationId) {
        mNativeMapView.removeAnnotation(annotationId);
        removeAnnotationsWithId(annotationId);
    }

    public void removeAnnotations() {
        long[] ids = new long[mAnnotations.size()];
        for (int i = 0; i < mAnnotations.size(); i++) {
            Annotation annotation = mAnnotations.get(i);
            long id = annotation.getId();
            ids[i] = id;
            if (annotation instanceof Marker) {
                ((Marker) annotation).hideInfoWindow();
            }
        }
        mNativeMapView.removeAnnotations(ids);
        mAnnotations.clear();
    }

    public List<Annotation> getAnnotations() {
        return Collections.unmodifiableList(mAnnotations);
    }

    public List<Annotation> getAnnotationsInBounds(BoundingBox bbox) {
        List<Annotation> annotations = new ArrayList<>();
        long[] ids = mNativeMapView.getAnnotationsInBounds(bbox);
        List<Long> idsList = new ArrayList<>();
        for (long id : ids) {
            idsList.add(id);
        }
        for (int i = 0; i < mAnnotations.size(); i++) {
            Annotation annotation = mAnnotations.get(i);
            if (annotation instanceof Marker && idsList.contains(annotation.getId())) {
                annotations.add(annotation);
            }
        }
        return annotations;
    }

    // Used by InfoWindow
    double getTopOffsetPixelsForAnnotationSymbol(@NonNull String symbolName) {
        return mNativeMapView.getTopOffsetPixelsForAnnotationSymbol(symbolName);
    }

    /**
     * Returns the distance spanned by one pixel at the specified latitude and current zoom level.
     * <p/>
     * The distance between pixels decreases as the latitude approaches the poles. This relationship parallels the relationship between longitudinal coordinates at different latitudes.
     *
     * @param latitude The latitude for which to return the value.
     * @return The distance (in meters) spanned by a single pixel.
     */
    public double getMetersPerPixelAtLatitude(double latitude) {
        return mNativeMapView.getMetersPerPixelAtLatitude(latitude, getZoomLevel());
    }

    // Used by InfoWindow
    float getScreenDensity() {
        return mScreenDensity;
    }

    private void selectAnnotation(Annotation annotation) {

        if (annotation == null) {
            return;
        }

        if (annotation == mSelectedAnnotation) {
            return;
        }

        if (annotation instanceof Marker) {
            // Need to deselect any currently selected annotation first
            deselectAnnotation();

            Marker marker = (Marker) annotation;
            boolean handledDefaultClick = false;
            if (mOnMarkerClickListener != null) {
                // end developer has provided a custom click listener
                handledDefaultClick = mOnMarkerClickListener.onMarkerClick(marker);
            }

            if (mInfoWindowAdapter != null) {
                // end developer is using a custom InfoWindowAdapter
                View content = mInfoWindowAdapter.getInfoWindow(marker);
                if (content != null) {
                    marker.showInfoWindow(content);
                }
            } else if (!handledDefaultClick) {
                // default behaviour
                // Can't do this as InfoWindow will get hidden
                //setCenterCoordinate(marker.getPosition(), true);
                marker.showInfoWindow();
            }

            mSelectedAnnotation = annotation;
        }
    }

    private void deselectAnnotation() {
        if (mSelectedAnnotation != null && mSelectedAnnotation instanceof Marker) {
            Marker marker = (Marker) mSelectedAnnotation;
            if (marker.isInfoWindowShown()) {
                marker.hideInfoWindow();
                mSelectedAnnotation = null;
            }
        }
    }


    //
    // Rendering
    //

    // Called when the map needs to be rerendered
    // Called via JNI from NativeMapView
    synchronized protected void onInvalidate() {
        if (!mDirty) {
            mDirty = true;
            postRender();
        }
    }

    private void postRender() {
        Runnable mRunnable = new Runnable() {
            @Override
            public void run() {
                updateCompass();
                updateGpsMarker();
                mNativeMapView.renderSync();
                mDirty = false;
            }
        };

        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            postOnAnimation(mRunnable);
        } else {
            postDelayed(mRunnable, 1000 / 60);
        }
    }

    public void onSizeChanged(int width, int height, int oldw, int oldh) {
        if (!isInEditMode()) {
            mNativeMapView.resizeView((int) (width / mScreenDensity), (int) (height / mScreenDensity));
        }
    }

    // This class handles TextureView callbacks
    private class SurfaceTextureListener implements TextureView.SurfaceTextureListener {

        // Called when the native surface texture has been created
        // Must do all EGL/GL ES initialization here
        @Override
        public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
            mNativeMapView.createSurface(new Surface(surface));
            mNativeMapView.resizeFramebuffer(width, height);
        }

        // Called when the native surface texture has been destroyed
        // Must do all EGL/GL ES destruction here
        @Override
        public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
            mNativeMapView.destroySurface();
            return true;
        }

        // Called when the format or size of the native surface texture has been changed
        // Must handle window resizing here.
        @Override
        public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
            mNativeMapView.resizeFramebuffer(width, height);
        }

        // Not used
        @Override
        public void onSurfaceTextureUpdated(SurfaceTexture surface) {
            // Do nothing
        }
    }

    //
    // View events
    //

    // Called when view is no longer connected
    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        // Required by ZoomButtonController (from Android SDK documentation)
        if (mZoomButtonsController != null) {
            mZoomButtonsController.setVisible(false);
        }
    }

    // Called when view is hidden and shown
    @Override
    protected void onVisibilityChanged(@NonNull View changedView, int visibility) {
        // Required by ZoomButtonController (from Android SDK documentation)
        if ((mZoomButtonsController != null) && (visibility != View.VISIBLE)) {
            mZoomButtonsController.setVisible(false);
        }
        if ((mZoomButtonsController != null) && (visibility == View.VISIBLE)
                && mZoomEnabled) {
            mZoomButtonsController.setVisible(true);
        }
    }

    //
    // Touch events
    //

    // Called when user touches the screen, all positions are absolute
    @Override
    public boolean onTouchEvent(@NonNull MotionEvent event) {
        // Check and ignore non touch or left clicks

        if ((event.getButtonState() != 0) && (event.getButtonState() != MotionEvent.BUTTON_PRIMARY)) {
            return false;
        }

        // Check two finger gestures first
        mRotateGestureDetector.onTouchEvent(event);
        mScaleGestureDetector.onTouchEvent(event);

        // Handle two finger tap
        switch (event.getActionMasked()) {
            case MotionEvent.ACTION_DOWN:
                // First pointer down
                mNativeMapView.setGestureInProgress(true);
                break;

            case MotionEvent.ACTION_POINTER_DOWN:
                // Second pointer down
                mTwoTap = event.getPointerCount() == 2;
                break;

            case MotionEvent.ACTION_POINTER_UP:
                // Second pointer up
                break;

            case MotionEvent.ACTION_UP:
                // First pointer up
                long tapInterval = event.getEventTime() - event.getDownTime();
                boolean isTap = tapInterval <= ViewConfiguration.getTapTimeout();
                boolean inProgress = mRotateGestureDetector.isInProgress() || mScaleGestureDetector.isInProgress();

                if (mTwoTap && isTap && !inProgress) {
                    PointF focalPoint = TwoFingerGestureDetector.determineFocalPoint(event);
                    zoom(false, focalPoint.x, focalPoint.y);
                    mTwoTap = false;
                    return true;
                }

                mTwoTap = false;
                mNativeMapView.setGestureInProgress(false);
                break;

            case MotionEvent.ACTION_CANCEL:
                mTwoTap = false;
                mNativeMapView.setGestureInProgress(false);
                break;
        }

        boolean retVal = mGestureDetector.onTouchEvent(event);
        return retVal || super.onTouchEvent(event);
    }

    // This class handles one finger gestures
    private class GestureListener extends
            GestureDetector.SimpleOnGestureListener {

        // Must always return true otherwise all events are ignored
        @Override
        public boolean onDown(MotionEvent e) {
            // Show the zoom controls
            if ((mZoomButtonsController != null) && mZoomEnabled) {
                mZoomButtonsController.setVisible(true);
            }

            return true;
        }

        // Called for double taps
        @Override
        public boolean onDoubleTap(MotionEvent e) {
            if (!mZoomEnabled) {
                return false;
            }

            // Single finger double tap
            // Zoom in
            zoom(true, e.getX(), e.getY());
            return true;
        }

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            // Cancel any animation
            mNativeMapView.cancelTransitions();
            return true;
        }

        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
            // Open / Close InfoWindow
            PointF tapPoint = new PointF(e.getX(), e.getY());

            float toleranceWidth = 40 * mScreenDensity;
            float toleranceHeight = 60 * mScreenDensity;

            RectF tapRect = new RectF(tapPoint.x - toleranceWidth / 2, tapPoint.y - 2 * toleranceHeight / 3,
                    tapPoint.x + toleranceWidth / 2, tapPoint.y + 1 * toleranceHeight / 3);

            List<LatLng> corners = Arrays.asList(
                    fromScreenLocation(new PointF(tapRect.left, tapRect.bottom)),
                    fromScreenLocation(new PointF(tapRect.left, tapRect.top)),
                    fromScreenLocation(new PointF(tapRect.right, tapRect.top)),
                    fromScreenLocation(new PointF(tapRect.right, tapRect.bottom))
            );

            BoundingBox tapBounds = BoundingBox.fromLatLngs(corners);

            List<Annotation> nearbyAnnotations = getAnnotationsInBounds(tapBounds);

            long newSelectedAnnotationID;

            if (nearbyAnnotations.size() > 0) {

                // there is at least one nearby annotation; select one
                //
                // first, sort for comparison and iteration
                Collections.sort(nearbyAnnotations);

                if (nearbyAnnotations == mAnnotationsNearLastTap) {
                    // the selection candidates haven't changed; cycle through them
                    if (mSelectedAnnotation != null && (mSelectedAnnotation.getId() == mAnnotationsNearLastTap.get(mAnnotationsNearLastTap.size() - 1).getId())) {
                        // the selected annotation is the last in the set; cycle back to the first
                        // note: this could be the selected annotation if only one in set
                        newSelectedAnnotationID = mAnnotationsNearLastTap.get(0).getId();
                    } else if (mSelectedAnnotation != null) {
                        // otherwise increment the selection through the candidates
                        long result = mAnnotationsNearLastTap.indexOf(mSelectedAnnotation);
                        newSelectedAnnotationID = mAnnotationsNearLastTap.get((int) result + 1).getId();
                    } else {
                        // no current selection; select the first one
                        newSelectedAnnotationID = mAnnotationsNearLastTap.get(0).getId();
                    }
                } else {
                    // start tracking a new set of nearby annotations
                    mAnnotationsNearLastTap = nearbyAnnotations;

                    // select the first one
                    newSelectedAnnotationID = mAnnotationsNearLastTap.get(0).getId();
                }

            } else {
                // there are no nearby annotations; deselect if necessary
                newSelectedAnnotationID = -1;
            }

            if (newSelectedAnnotationID >= 0) {

                for (Annotation annotation : mAnnotations) {
                    if (annotation instanceof Marker) {
                        if (annotation.getId() == newSelectedAnnotationID) {
                            if (mSelectedAnnotation == null || annotation.getId() != mSelectedAnnotation.getId()) {
                                selectAnnotation(annotation);
                            }
                            break;
                        }
                    }
                }

            } else {
                // deselect any selected annotation
                if (mSelectedAnnotation != null) {
                    deselectAnnotation();
                }

                // notify app of map click
                if (mOnMapClickListener != null) {
                    LatLng point = fromScreenLocation(tapPoint);
                    mOnMapClickListener.onMapClick(point);
                }
            }

            return true;
        }

        // Called for a long press
        @Override
        public void onLongPress(MotionEvent e) {
            if (mOnMapLongClickListener != null) {
                LatLng point = fromScreenLocation(new PointF(e.getX(), e.getY()));
                mOnMapLongClickListener.onMapLongClick(point);
            }
        }

        // Called for flings
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                               float velocityY) {
            if (!mScrollEnabled) {
                return false;
            }

            // Fling the map
            // TODO Google Maps also has a rotate and zoom fling

            float ease = 0.25f;

            velocityX = velocityX * ease;
            velocityY = velocityY * ease;

            double speed = Math.sqrt(velocityX * velocityX + velocityY * velocityY);
            double deceleration = 2500;
            double duration = speed / (deceleration * ease);

            // Cancel any animation
            mNativeMapView.cancelTransitions();

            mNativeMapView.moveBy(velocityX * duration / 2.0 / mScreenDensity, velocityY * duration / 2.0 / mScreenDensity, (long) (duration * 1000.0f));

            if (mOnFlingListener != null) {
                mOnFlingListener.onFling();
            }

            return true;
        }

        // Called for drags
        // TODO use MoveGestureDetector
        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            if (!mScrollEnabled) {
                return false;
            }

            // Cancel any animation
            mNativeMapView.cancelTransitions(); // TODO need to test canceling
            // transitions with touch

            // Scroll the map
            mNativeMapView.moveBy(-distanceX / mScreenDensity, -distanceY / mScreenDensity);

            if (mOnScrollListener != null) {
                mOnScrollListener.onScroll();
            }

            return true;
        }
    }

    // This class handles two finger gestures
    private class ScaleGestureListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {

        long mBeginTime = 0;
        float mScaleFactor = 1.0f;
        boolean mStarted = false;

        // Called when two fingers first touch the screen
        @Override
        public boolean onScaleBegin(ScaleGestureDetector detector) {
            if (!mZoomEnabled) {
                return false;
            }

            mBeginTime = detector.getEventTime();
            return true;
        }

        // Called when fingers leave screen
        @Override
        public void onScaleEnd(ScaleGestureDetector detector) {
            mBeginTime = 0;
            mScaleFactor = 1.0f;
            mStarted = false;
        }

        // Called each time one of the two fingers moves
        // Called for pinch zooms
        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            if (!mZoomEnabled) {
                return false;
            }

            // If scale is large enough ignore a tap
            // TODO: Google Maps seem to use a velocity rather than absolute
            // value?
            mScaleFactor *= detector.getScaleFactor();
            if ((mScaleFactor > 1.05f) || (mScaleFactor < 0.95f)) {
                mStarted = true;
            }

            // Ignore short touches in case it is a tap
            // Also ignore small scales
            long time = detector.getEventTime();
            long interval = time - mBeginTime;
            if (!mStarted && (interval <= ViewConfiguration.getTapTimeout())) {
                return false;
            }

            // TODO complex decision between rotate or scale or both (see Google
            // Maps app)

            // Cancel any animation
            mNativeMapView.cancelTransitions();

            // Scale the map
            mNativeMapView.scaleBy(detector.getScaleFactor(), detector.getFocusX() / mScreenDensity, detector.getFocusY() / mScreenDensity);

            return true;
        }
    }

    // This class handles two finger rotate gestures
    // TODO need way to single finger rotate - need to research how google maps
    // does this - for phones with single touch, or when using mouse etc
    private class RotateGestureListener extends RotateGestureDetector.SimpleOnRotateGestureListener {

        long mBeginTime = 0;
        float mTotalAngle = 0.0f;
        boolean mStarted = false;

        // Called when two fingers first touch the screen
        @Override
        public boolean onRotateBegin(RotateGestureDetector detector) {
            if (!mRotateEnabled) {
                return false;
            }

            mBeginTime = detector.getEventTime();
            return true;
        }

        // Called when the fingers leave the screen
        @Override
        public void onRotateEnd(RotateGestureDetector detector) {
            mBeginTime = 0;
            mTotalAngle = 0.0f;
            mStarted = false;
        }

        // Called each time one of the two fingers moves
        // Called for rotation
        @Override
        public boolean onRotate(RotateGestureDetector detector) {
            if (!mRotateEnabled) {
                return false;
            }

            // If rotate is large enough ignore a tap
            // TODO: Google Maps seem to use a velocity rather than absolute
            // value, up to a point then they always rotate
            mTotalAngle += detector.getRotationDegreesDelta();
            if ((mTotalAngle > 5.0f) || (mTotalAngle < -5.0f)) {
                mStarted = true;
            }

            // Ignore short touches in case it is a tap
            // Also ignore small rotate
            long time = detector.getEventTime();
            long interval = time - mBeginTime;
            if (!mStarted && (interval <= ViewConfiguration.getTapTimeout())) {
                return false;
            }

            // TODO complex decision between rotate or scale or both (see Google
            // Maps app). It seems if you start one or the other it takes more
            // to start the other too. Haven't figured out what it uses to
            // decide when to transition to both at the same time.

            // Cancel any animation
            mNativeMapView.cancelTransitions();

            // Rotate the map
            double bearing = mNativeMapView.getBearing();
            bearing += detector.getRotationDegreesDelta();
            mNativeMapView.setBearing(bearing, detector.getFocusX() / mScreenDensity, detector.getFocusY() / mScreenDensity);

            return true;
        }
    }

    // This class handles input events from the zoom control buttons
    // Zoom controls allow single touch only devices to zoom in and out
    private class OnZoomListener implements ZoomButtonsController.OnZoomListener {

        // Not used
        @Override
        public void onVisibilityChanged(boolean visible) {
            // Ignore
        }

        // Called when user pushes a zoom button
        @Override
        public void onZoom(boolean zoomIn) {
            if (!mZoomEnabled) {
                return;
            }

            // Zoom in or out
            zoom(zoomIn);
        }
    }

    //
    // Input events
    //

    // Called when the user presses a key, also called for repeating keys held
    // down
    @Override
    public boolean onKeyDown(int keyCode, @NonNull KeyEvent event) {
        // If the user has held the scroll key down for a while then accelerate
        // the scroll speed
        double scrollDist = event.getRepeatCount() >= 5 ? 50.0 : 10.0;

        // Check which key was pressed via hardware/real key code
        switch (keyCode) {
            // Tell the system to track these keys for long presses on
            // onKeyLongPress is fired
            case KeyEvent.KEYCODE_ENTER:
            case KeyEvent.KEYCODE_DPAD_CENTER:
                event.startTracking();
                return true;

            case KeyEvent.KEYCODE_DPAD_LEFT:
                if (!mScrollEnabled) {
                    return false;
                }

                // Cancel any animation
                mNativeMapView.cancelTransitions();

                // Move left
                mNativeMapView.moveBy(scrollDist / mScreenDensity, 0.0 / mScreenDensity);
                return true;

            case KeyEvent.KEYCODE_DPAD_RIGHT:
                if (!mScrollEnabled) {
                    return false;
                }

                // Cancel any animation
                mNativeMapView.cancelTransitions();

                // Move right
                mNativeMapView.moveBy(-scrollDist / mScreenDensity, 0.0 / mScreenDensity);
                return true;

            case KeyEvent.KEYCODE_DPAD_UP:
                if (!mScrollEnabled) {
                    return false;
                }

                // Cancel any animation
                mNativeMapView.cancelTransitions();

                // Move up
                mNativeMapView.moveBy(0.0 / mScreenDensity, scrollDist / mScreenDensity);
                return true;

            case KeyEvent.KEYCODE_DPAD_DOWN:
                if (!mScrollEnabled) {
                    return false;
                }

                // Cancel any animation
                mNativeMapView.cancelTransitions();

                // Move down
                mNativeMapView.moveBy(0.0 / mScreenDensity, -scrollDist / mScreenDensity);
                return true;

            default:
                // We are not interested in this key
                return super.onKeyUp(keyCode, event);
        }
    }

    // Called when the user long presses a key that is being tracked
    @Override
    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
        // Check which key was pressed via hardware/real key code
        switch (keyCode) {
            // Tell the system to track these keys for long presses on
            // onKeyLongPress is fired
            case KeyEvent.KEYCODE_ENTER:
            case KeyEvent.KEYCODE_DPAD_CENTER:
                if (!mZoomEnabled) {
                    return false;
                }

                // Zoom out
                zoom(false);
                return true;

            default:
                // We are not interested in this key
                return super.onKeyUp(keyCode, event);
        }
    }

    // Called when the user releases a key
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        // Check if the key action was canceled (used for virtual keyboards)
        if (event.isCanceled()) {
            return super.onKeyUp(keyCode, event);
        }

        // Check which key was pressed via hardware/real key code
        // Note if keyboard does not have physical key (ie primary non-shifted
        // key) then it will not appear here
        // Must use the key character map as physical to character is not
        // fixed/guaranteed
        switch (keyCode) {
            case KeyEvent.KEYCODE_ENTER:
            case KeyEvent.KEYCODE_DPAD_CENTER:
                if (!mZoomEnabled) {
                    return false;
                }

                // Zoom in
                zoom(true);
                return true;
        }

        // We are not interested in this key
        return super.onKeyUp(keyCode, event);
    }

    // Called for trackball events, all motions are relative in device specific
    // units
    @Override
    public boolean onTrackballEvent(MotionEvent event) {
        // Choose the action
        switch (event.getActionMasked()) {
            // The trackball was rotated
            case MotionEvent.ACTION_MOVE:
                if (!mScrollEnabled) {
                    return false;
                }

                // Cancel any animation
                mNativeMapView.cancelTransitions();

                // Scroll the map
                mNativeMapView.moveBy(-10.0 * event.getX() / mScreenDensity, -10.0 * event.getY() / mScreenDensity);
                return true;

            // Trackball was pushed in so start tracking and tell system we are
            // interested
            // We will then get the up action
            case MotionEvent.ACTION_DOWN:
                // Set up a delayed callback to check if trackball is still
                // After waiting the system long press time out
                if (mCurrentTrackballLongPressTimeOut != null) {
                    mCurrentTrackballLongPressTimeOut.cancel();
                    mCurrentTrackballLongPressTimeOut = null;
                }
                mCurrentTrackballLongPressTimeOut = new TrackballLongPressTimeOut();
                postDelayed(mCurrentTrackballLongPressTimeOut,
                        ViewConfiguration.getLongPressTimeout());
                return true;

            // Trackball was released
            case MotionEvent.ACTION_UP:
                if (!mZoomEnabled) {
                    return false;
                }

                // Only handle if we have not already long pressed
                if (mCurrentTrackballLongPressTimeOut != null) {
                    // Zoom in
                    zoom(true);
                }
                return true;

            // Trackball was cancelled
            case MotionEvent.ACTION_CANCEL:
                if (mCurrentTrackballLongPressTimeOut != null) {
                    mCurrentTrackballLongPressTimeOut.cancel();
                    mCurrentTrackballLongPressTimeOut = null;
                }
                return true;

            default:
                // We are not interested in this event
                return super.onTrackballEvent(event);
        }
    }

    // This class implements the trackball long press time out callback
    private class TrackballLongPressTimeOut implements Runnable {

        // Track if we have been cancelled
        private boolean cancelled;

        public TrackballLongPressTimeOut() {
            cancelled = false;
        }

        // Cancel the timeout
        public void cancel() {
            cancelled = true;
        }

        // Called when long press time out expires
        @Override
        public void run() {
            // Check if the trackball is still pressed
            if (!cancelled) {
                // Zoom out
                zoom(false);

                // Ensure the up action is not run
                mCurrentTrackballLongPressTimeOut = null;
            }
        }
    }

    // Called for events that don't fit the other handlers
    // such as mouse scroll events, mouse moves, joystick, trackpad
    @Override
    public boolean onGenericMotionEvent(MotionEvent event) {
        // Mouse events
        //if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) { // this is not available before API 18
        if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) == InputDevice.SOURCE_CLASS_POINTER) {
            // Choose the action
            switch (event.getActionMasked()) {
                // Mouse scrolls
                case MotionEvent.ACTION_SCROLL:
                    if (!mZoomEnabled) {
                        return false;
                    }

                    // Cancel any animation
                    mNativeMapView.cancelTransitions();

                    // Get the vertical scroll amount, one click = 1
                    float scrollDist = event.getAxisValue(MotionEvent.AXIS_VSCROLL);

                    // Scale the map by the appropriate power of two factor
                    mNativeMapView.scaleBy(Math.pow(2.0, scrollDist), event.getX() / mScreenDensity, event.getY() / mScreenDensity);

                    return true;

                default:
                    // We are not interested in this event
                    return super.onGenericMotionEvent(event);
            }
        }

        // We are not interested in this event
        return super.onGenericMotionEvent(event);
    }

    // Called when the mouse pointer enters or exits the view
    // or when it fades in or out due to movement
    @Override
    public boolean onHoverEvent(@NonNull MotionEvent event) {
        switch (event.getActionMasked()) {
            case MotionEvent.ACTION_HOVER_ENTER:
            case MotionEvent.ACTION_HOVER_MOVE:
                // Show the zoom controls
                if ((mZoomButtonsController != null) && mZoomEnabled) {
                    mZoomButtonsController.setVisible(true);
                }
                return true;

            case MotionEvent.ACTION_HOVER_EXIT:
                // Hide the zoom controls
                if (mZoomButtonsController != null) {
                    mZoomButtonsController.setVisible(false);
                }

            default:
                // We are not interested in this event
                return super.onHoverEvent(event);
        }
    }

    //
    // Connectivity events
    //

    // This class handles connectivity changes
    class ConnectivityReceiver extends BroadcastReceiver {

        // Called when an action we are listening to in the manifest has been sent
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
                onConnectivityChanged(!noConnectivity);
            }
        }
    }

    // Called when our Internet connectivity has changed
    private void onConnectivityChanged(boolean isConnected) {
        mNativeMapView.setReachability(isConnected);
    }

    //
    // Map events
    //

    /**
     * Add an OnMapChangedListener
     *
     * @param listener Listener to add
     */
    public void addOnMapChangedListener(@NonNull OnMapChangedListener listener) {
        if (listener != null) {
            mOnMapChangedListener.add(listener);
        }
    }

    /**
     * Add an InfoWindowAdapter
     *
     * @param infoWindowAdapter to set
     */
    public void setInfoWindowAdapter(@NonNull InfoWindowAdapter infoWindowAdapter) {
        mInfoWindowAdapter = infoWindowAdapter;
    }

    /**
     * Remove an OnMapChangedListener
     *
     * @param listener Listener to remove
     */
    public void removeOnMapChangedListener(@NonNull OnMapChangedListener listener) {
        if (listener != null) {
            mOnMapChangedListener.remove(listener);
        }
    }

    // Called when the map view transformation has changed
    // Called via JNI from NativeMapView
    // Need to update anything that relies on map state
    protected void onMapChanged(int rawChange) {
        final MapChange change = MapChange.fromInteger(rawChange);
        if (mOnMapChangedListener != null) {
            post(new Runnable() {
                @Override
                public void run() {
                    for (OnMapChangedListener listener : mOnMapChangedListener) {
                        listener.onMapChanged(change);
                    }
                }
            });
        }
    }

    private OnFpsChangedListener mOnFpsChangedListener;

    // Adds a listener for onFpsChanged
    public void setOnFpsChangedListener(OnFpsChangedListener listener) {
        mOnFpsChangedListener = listener;
    }

    // Called when debug mode is enabled to update a FPS counter
    // Called via JNI from NativeMapView
    protected void onFpsChanged(final double fps) {
        if (mOnFpsChangedListener != null) {
            post(new Runnable() {
                @Override
                public void run() {
                    mOnFpsChangedListener.onFpsChanged(fps);
                }
            });
        }
    }

    public void setOnScrollListener(OnScrollListener onScrollListener) {
        mOnScrollListener = onScrollListener;
    }

    public void setOnFlingListener(OnFlingListener onFlingListener) {
        mOnFlingListener = onFlingListener;
    }

    public void setOnMapClickListener(OnMapClickListener onMapClickListener) {
        mOnMapClickListener = onMapClickListener;
    }

    public void setOnMapLongClickListener(OnMapLongClickListener onMapLongClickListener) {
        mOnMapLongClickListener = onMapLongClickListener;
    }

    public void setOnMarkerClickListener(OnMarkerClickListener onMarkerClickListener) {
        mOnMarkerClickListener = onMarkerClickListener;
    }

    //
    // User location
    //

    /**
     * Gets the status of the my-location layer.
     *
     * @return True if the my-location layer is enabled, false otherwise.
     */
    public final boolean isMyLocationEnabled() {
        return mIsMyLocationEnabled;
    }

    /**
     * Enables or disables the my-location layer.
     * While enabled, the my-location layer continuously draws an indication of a user's current
     * location and bearing, and displays UI controls that allow a user to interact with their
     * location (for example, to enable or disable camera tracking of their location and bearing).
     *
     * @param enabled True to enable; false to disable.
     */
    public final void setMyLocationEnabled(boolean enabled) {
        mIsMyLocationEnabled = enabled;
        toggleGps(enabled);
    }

    /**
     * Returns the currently displayed user location, or null if there is no location data available.
     *
     * @return The currently displayed user location.
     */
    public final Location getMyLocation() {
        return mGpsLocation;
    }

    /**
     * Enabled / Disable GPS location updates along with updating the UI
     *
     * @param enableGps true if GPS is to be enabled, false if GPS is to be disabled
     */
    private void toggleGps(boolean enableGps) {
        if (enableGps) {
            if (!mLocationClient.isConnected()) {
                mGpsLocation = null;
                mLocationClient.connect();
                updateLocation(LocationServices.FusedLocationApi.getLastLocation());
                LocationServices.FusedLocationApi.requestLocationUpdates(mLocationRequest, this);
                mCompassView.registerListeners(this);
            }
        } else {
            if (mLocationClient.isConnected()) {
                mCompassView.unRegisterListeners();
                LocationServices.FusedLocationApi.removeLocationUpdates(this);
                mLocationClient.disconnect();
                mGpsLocation = null;
            }
        }

        onInvalidate();
    }

    /**
     * LOST's LocationListener Callback
     *
     * @param location New Location
     */
    @Override
    public void onLocationChanged(Location location) {
        updateLocation(location);
    }

    // Handles location updates from GPS
    private void updateLocation(Location location) {
        if (location != null) {
            mGpsLocation = location;
            updateGpsMarker();
        }
    }

    private void updateGpsMarker() {
        if (isMyLocationEnabled() && mGpsLocation != null) {
            mGpsMarker.setVisibility(View.VISIBLE);
            LatLng coordinate = new LatLng(mGpsLocation);
            PointF screenLocation = toScreenLocation(coordinate);

            float iconSize = 27.0f * mScreenDensity;
            // Update Location
            FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams((int) iconSize, (int) iconSize);
            lp.leftMargin = (int) (screenLocation.x - iconSize / 2.0f);
            lp.topMargin = (int) (screenLocation.y + iconSize / 2.0f);
            mGpsMarker.setLayoutParams(lp);
            rotateImageView(mGpsMarker, 0.0f);
            mGpsMarker.requestLayout();
/*
            // Used For User Location Bearing UI
            if (mGpsLocation.hasBearing() || mCompassValid) {
                mGpsMarker.setImageResource(R.drawable.direction_arrow);
                float iconSize = 54.0f * mScreenDensity;
                FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams((int) iconSize, (int) iconSize);
                lp.leftMargin = (int) (screenLocation.x - iconSize / 2.0f);
                lp.topMargin = mMapFrameLayout.getHeight() - (int) (screenLocation.y + iconSize / 2.0f);
                mGpsMarker.setLayoutParams(lp);
                float bearing = mGpsLocation.hasBearing() ? mGpsLocation.getBearing() : mCompassBearing;
                rotateImageView(mGpsMarker, bearing);
                mGpsMarker.requestLayout();
            }
*/
        } else {
            if (mGpsMarker != null) {
                mGpsMarker.setVisibility(View.INVISIBLE);
            }
        }
    }

    //
    // Compass
    //

    /**
     * Gets whether the compass is enabled/disabled.
     *
     * @return true if the compass is enabled; false if the compass is disabled.
     */
    public boolean isCompassEnabled() {
        return mCompassView.isEnabled();
    }

    /**
     * Enables or disables the compass. The compass is an icon on the map that indicates the
     * direction of north on the map. If enabled, it is only shown when the camera is tilted or
     * rotated away from its default orientation (tilt of 0 and a bearing of 0). When a user clicks
     * the compass, the camera orients itself to its default orientation and fades away shortly
     * after. If disabled, the compass will never be displayed.
     * <p/>
     * By default, the compass is enabled
     *
     * @param compassEnabled true to enable the compass; false to disable the compass.
     */
    public void setCompassEnabled(boolean compassEnabled) {
        mCompassView.setEnabled(compassEnabled);
        onInvalidate();
    }

    public void setCompassGravity(int gravity) {
        setWidgetGravity(mCompassView, gravity);
    }

    public void setCompassMargins(int left, int top, int right, int bottom) {
        setWidgetMargins(mCompassView, left, top, right, bottom);
    }

    // Rotates an ImageView - does not work if the ImageView has padding, use margins
    private void rotateImageView(ImageView imageView, float angle) {
        Matrix matrix = new Matrix();
        matrix.setScale((float) imageView.getWidth() / (float) imageView.getDrawable().getIntrinsicWidth(), (float) imageView.getHeight() / (float) imageView.getDrawable().getIntrinsicHeight());
        matrix.postRotate(angle, (float) imageView.getWidth() / 2.0f, (float) imageView.getHeight() / 2.0f);
        imageView.setImageMatrix(matrix);
        imageView.setScaleType(ImageView.ScaleType.MATRIX);
    }

    // Updates the UI to match the current map's position
    private void updateCompass() {
        if (isCompassEnabled()) {
            mCompassView.setVisibility(VISIBLE);
            rotateImageView(mCompassView, (float) getDirection());
        } else {
            mCompassView.setVisibility(INVISIBLE);
        }
    }

    @Override
    public Location getLocation() {
        return mGpsLocation;
    }

    //
    // Logo
    //

    public void setLogoGravity(int gravity) {
        setWidgetGravity(mLogoView, gravity);
    }

    public void setLogoMargins(int left, int top, int right, int bottom) {
        setWidgetMargins(mLogoView, left, top, right, bottom);
    }

    public void setLogoVisibility(int visibility) {
        mLogoView.setVisibility(visibility);
    }

    public void setAttributionGravity(int gravity) {
        setWidgetGravity(mAttributionsView, gravity);
    }

    public void setAttributionMargins(int left, int top, int right, int bottom) {
        setWidgetMargins(mAttributionsView, left, top, right, bottom);
    }

    public void setAttributionVisibility(int visibility) {
        mAttributionsView.setVisibility(visibility);
    }

    private void setWidgetGravity(@NonNull final View view, int gravity) {
        LayoutParams layoutParams = (LayoutParams) view.getLayoutParams();
        layoutParams.gravity = gravity;
        view.setLayoutParams(layoutParams);
    }

    private void setWidgetMargins(@NonNull final View view, int left, int top, int right, int bottom) {
        LayoutParams layoutParams = (LayoutParams) view.getLayoutParams();
        layoutParams.setMargins(left, top, right, bottom);
        view.setLayoutParams(layoutParams);
    }

    private void setWidgetMargins(@NonNull final View view, float leftDp, float topDp, float rightDp, float bottomDp) {
        LayoutParams layoutParams = (LayoutParams) view.getLayoutParams();
        layoutParams.setMargins((int) (leftDp * mScreenDensity), (int) (topDp * mScreenDensity), (int) (rightDp * mScreenDensity), (int) (bottomDp * mScreenDensity));
        view.setLayoutParams(layoutParams);
    }

    //
    // Attribution
    //

    private static class AttributionOnClickListener implements View.OnClickListener, DialogInterface.OnClickListener {

        private MapView mMapView;

        public AttributionOnClickListener(MapView mapView) {
            mMapView = mapView;
        }

        // Called when someone presses the attribution icon
        @Override
        public void onClick(View v) {
            Context context = v.getContext();
            String[] items = context.getResources().getStringArray(R.array.attribution_names);
            AlertDialog.Builder builder = new AlertDialog.Builder(context, R.style.AttributionAlertDialogStyle);
            builder.setTitle(R.string.attributionsDialogTitle);
            builder.setAdapter(new ArrayAdapter<>(context, R.layout.attribution_list_item, items), this);
            builder.show();
        }

        // Called when someone selects an attribution, 'Improve this map' adds location data to the url
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Context context = ((Dialog) dialog).getContext();
            String url = context.getResources().getStringArray(R.array.attribution_links)[which];
            if (which == ATTRIBUTION_INDEX_IMPROVE_THIS_MAP) {
                LatLng latLng = mMapView.getCenterCoordinate();
                url = String.format(url, latLng.getLongitude(), latLng.getLatitude(), (int) mMapView.getZoomLevel());
            }
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse(url));
            context.startActivity(intent);
        }
    }
}