RMMapView.m 144 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 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 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913
//
//  RMMapView.m
//
// Copyright (c) 2008-2013, Route-Me Contributors
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
//   list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

#import "RMMapView.h"
#import "RMMapViewDelegate.h"
#import "RMPixel.h"

#import "RMFoundation.h"
#import "RMProjection.h"
#import "RMMarker.h"
#import "RMCircle.h"
#import "RMShape.h"
#import "RMAnnotation.h"
#import "RMQuadTree.h"
#import "RMPointAnnotation.h"

#import "RMFractalTileProjection.h"

#import "RMTileCache.h"
#import "RMTileSource.h"
#import "RMMapBoxSource.h"

#import "RMMapTiledLayerView.h"
#import "RMMapOverlayView.h"
#import "RMLoadingTileView.h"

#import "RMUserLocation.h"
#import "RMUserTrackingBarButtonItem.h"

#import "RMAttributionViewController.h"

#import "SMCalloutView.h"

#pragma mark --- begin constants ----

#define kZoomRectPixelBuffer 150.0

#define kDefaultInitialLatitude  38.913175
#define kDefaultInitialLongitude -77.032458

#define kDefaultMinimumZoomLevel 0.0
#define kDefaultMaximumZoomLevel 25.0
#define kDefaultInitialZoomLevel 11.0

#define kRMTrackingHaloAnnotationTypeName   @"RMTrackingHaloAnnotation"
#define kRMAccuracyCircleAnnotationTypeName @"RMAccuracyCircleAnnotation"

#pragma mark --- end constants ----

@interface RMMapView (PrivateMethods) <UIScrollViewDelegate,
                                       UIGestureRecognizerDelegate,
                                       RMMapScrollViewDelegate,
                                       CLLocationManagerDelegate,
                                       SMCalloutViewDelegate,
                                       UIPopoverControllerDelegate,
                                       UIViewControllerTransitioningDelegate,
                                       UIViewControllerAnimatedTransitioning>

@property (nonatomic, assign) UIViewController *viewControllerPresentingAttribution;
@property (nonatomic, retain) RMUserLocation *userLocation;

- (void)createMapView;

- (void)registerMoveEventByUser:(BOOL)wasUserEvent;
- (void)completeMoveEventAfterDelay:(NSTimeInterval)delay;
- (void)registerZoomEventByUser:(BOOL)wasUserEvent;
- (void)completeZoomEventAfterDelay:(NSTimeInterval)delay;

- (void)correctPositionOfAllAnnotations;
- (void)correctPositionOfAllAnnotationsIncludingInvisibles:(BOOL)correctAllLayers animated:(BOOL)animated;
- (void)correctOrderingOfAllAnnotations;

- (void)updateHeadingForDeviceOrientation;

@end

#pragma mark -

@interface RMUserLocation (PrivateMethods)

@property (nonatomic, getter=isUpdating) BOOL updating;
@property (nonatomic, retain) CLLocation *location;
@property (nonatomic, retain) CLHeading *heading;
@property (nonatomic, assign) BOOL hasCustomLayer;

- (void)updateTintColor;

@end

#pragma mark -

@interface RMAnnotation (PrivateMethods)

@property (nonatomic, assign) BOOL isUserLocationAnnotation;

@end

#pragma mark -

@interface RMUserTrackingBarButtonItem (PrivateMethods)

@property (nonatomic, assign) UIViewTintAdjustmentMode tintAdjustmentMode;

@end

#pragma mark -

@implementation RMMapView
{
    id <RMMapViewDelegate> _delegate;

    BOOL _delegateHasBeforeMapMove;
    BOOL _delegateHasAfterMapMove;
    BOOL _delegateHasBeforeMapZoom;
    BOOL _delegateHasAfterMapZoom;
    BOOL _delegateHasMapViewRegionDidChange;
    BOOL _delegateHasDoubleTapOnMap;
    BOOL _delegateHasSingleTapOnMap;
    BOOL _delegateHasSingleTapTwoFingersOnMap;
    BOOL _delegateHasLongPressOnMap;
    BOOL _delegateHasTapOnAnnotation;
    BOOL _delegateHasDoubleTapOnAnnotation;
    BOOL _delegateHasLongPressOnAnnotation;
    BOOL _delegateHasTapOnCalloutAccessoryControlForAnnotation;
    BOOL _delegateHasTapOnLabelForAnnotation;
    BOOL _delegateHasDoubleTapOnLabelForAnnotation;
    BOOL _delegateHasShouldDragMarker;
    BOOL _delegateHasDidDragMarker;
    BOOL _delegateHasDidEndDragMarker;
    BOOL _delegateHasLayerForAnnotation;
    BOOL _delegateHasWillHideLayerForAnnotation;
    BOOL _delegateHasDidHideLayerForAnnotation;
    BOOL _delegateHasDidSelectAnnotation;
    BOOL _delegateHasDidDeselectAnnotation;
    BOOL _delegateHasWillStartLocatingUser;
    BOOL _delegateHasDidStopLocatingUser;
    BOOL _delegateHasDidUpdateUserLocation;
    BOOL _delegateHasDidFailToLocateUserWithError;
    BOOL _delegateHasDidChangeUserTrackingMode;

    UIView *_backgroundView;
    RMMapScrollView *_mapScrollView;
    RMMapOverlayView *_overlayView;
    UIView *_tiledLayersSuperview;
    RMLoadingTileView *_loadingTileView;

    RMProjection *_projection;
    RMFractalTileProjection *_mercatorToTileProjection;
    RMTileSourcesContainer *_tileSourcesContainer;

    NSMutableSet *_annotations;
    NSMutableSet *_visibleAnnotations;

    BOOL _constrainMovement, _constrainMovementByUser;
    RMProjectedRect _constrainingProjectedBounds, _constrainingProjectedBoundsByUser;

    double _metersPerPixel;
    float _zoom, _lastZoom;
    CGPoint _lastContentOffset, _accumulatedDelta;
    CGSize _lastContentSize;
    BOOL _mapScrollViewIsZooming;

    BOOL _draggingEnabled, _bouncingEnabled;

    CGPoint _lastDraggingTranslation;
    RMAnnotation *_draggedAnnotation;

    CLLocationManager *_locationManager;

    RMAnnotation *_accuracyCircleAnnotation;
    RMAnnotation *_trackingHaloAnnotation;

    UIImageView *_userLocationTrackingView;
    UIImageView *_userHeadingTrackingView;
    UIImageView *_userHaloTrackingView;

    RMUserTrackingBarButtonItem *_userTrackingBarButtonItem;

    UIViewController *_viewControllerPresentingAttribution;
    UIButton *_attributionButton;
    UIPopoverController *_attributionPopover;

    CGAffineTransform _mapTransform;
    CATransform3D _annotationTransform;

    NSOperationQueue *_moveDelegateQueue;
    NSOperationQueue *_zoomDelegateQueue;

    UIImageView *_logoBug;

    UIButton *_compassButton;

    RMAnnotation *_currentAnnotation;
    SMCalloutView *_currentCallout;

    BOOL _rotateAtMinZoom;
}

@synthesize decelerationMode = _decelerationMode;

@synthesize zoomingInPivotsAroundCenter = _zoomingInPivotsAroundCenter;
@synthesize minZoom = _minZoom, maxZoom = _maxZoom;
@synthesize screenScale = _screenScale;
@synthesize tileCache = _tileCache;
@synthesize quadTree = _quadTree;
@synthesize clusteringEnabled = _clusteringEnabled;
@synthesize positionClusterMarkersAtTheGravityCenter = _positionClusterMarkersAtTheGravityCenter;
@synthesize orderMarkersByYPosition = _orderMarkersByYPosition;
@synthesize orderClusterMarkersAboveOthers = _orderClusterMarkersAboveOthers;
@synthesize clusterMarkerSize = _clusterMarkerSize, clusterAreaSize = _clusterAreaSize;
@synthesize adjustTilesForRetinaDisplay = _adjustTilesForRetinaDisplay;
@synthesize userLocation = _userLocation;
@synthesize showsUserLocation = _showsUserLocation;
@synthesize userTrackingMode = _userTrackingMode;
@synthesize displayHeadingCalibration = _displayHeadingCalibration;
@synthesize missingTilesDepth = _missingTilesDepth;
@synthesize debugTiles = _debugTiles;
@synthesize hideAttribution = _hideAttribution;
@synthesize showLogoBug = _showLogoBug;

#pragma mark -
#pragma mark Initialization

- (void)performInitializationWithTilesource:(id <RMTileSource>)newTilesource
                           centerCoordinate:(CLLocationCoordinate2D)initialCenterCoordinate
                                  zoomLevel:(float)initialTileSourceZoomLevel
                               maxZoomLevel:(float)initialTileSourceMaxZoomLevel
                               minZoomLevel:(float)initialTileSourceMinZoomLevel
                            backgroundImage:(UIImage *)backgroundImage
{
    _constrainMovement = _constrainMovementByUser = _bouncingEnabled = _zoomingInPivotsAroundCenter = NO;
    _draggingEnabled = YES;

    _lastDraggingTranslation = CGPointZero;
    _draggedAnnotation = nil;

    self.backgroundColor = (RMPostVersion6 ? [UIColor colorWithRed:0.970 green:0.952 blue:0.912 alpha:1.000] : [UIColor grayColor]);

    self.clipsToBounds = YES;

    _tileSourcesContainer = [RMTileSourcesContainer new];
    _tiledLayersSuperview = nil;

    _projection = nil;
    _mercatorToTileProjection = nil;
    _mapScrollView = nil;
    _overlayView = nil;

    _screenScale = [UIScreen mainScreen].scale;

    _adjustTilesForRetinaDisplay = NO;
    _missingTilesDepth = 1;
    _debugTiles = NO;

    _orderMarkersByYPosition = YES;
    _orderClusterMarkersAboveOthers = YES;

    _annotations = [NSMutableSet new];
    _visibleAnnotations = [NSMutableSet new];
    [self setQuadTree:[[RMQuadTree alloc] initWithMapView:self]];
    _clusteringEnabled = NO;
    _positionClusterMarkersAtTheGravityCenter = YES;
    _clusterMarkerSize = CGSizeMake(100.0, 100.0);
    _clusterAreaSize = CGSizeMake(150.0, 150.0);

    _moveDelegateQueue = [NSOperationQueue new];
    [_moveDelegateQueue setMaxConcurrentOperationCount:1];

    _zoomDelegateQueue = [NSOperationQueue new];
    [_zoomDelegateQueue setMaxConcurrentOperationCount:1];

    [self setTileCache:[RMTileCache new]];

    if (backgroundImage)
    {
        [self setBackgroundView:[[UIView alloc] initWithFrame:[self bounds]]];
        self.backgroundView.layer.contents = (id)backgroundImage.CGImage;
    }
    else
    {
        [self setBackgroundView:nil];
    }

    if (initialTileSourceMinZoomLevel < newTilesource.minZoom) initialTileSourceMinZoomLevel = newTilesource.minZoom;
    if (initialTileSourceMaxZoomLevel > newTilesource.maxZoom) initialTileSourceMaxZoomLevel = newTilesource.maxZoom;
    [self setTileSourcesMinZoom:initialTileSourceMinZoomLevel];
    [self setTileSourcesMaxZoom:initialTileSourceMaxZoomLevel];
    [self setTileSourcesZoom:initialTileSourceZoomLevel];

    [self setTileSource:newTilesource];
    [self setCenterCoordinate:initialCenterCoordinate animated:NO];

    [self setDecelerationMode:RMMapDecelerationFast];

    self.showLogoBug = YES;

    if (RMPostVersion7)
    {
        _compassButton = [UIButton buttonWithType:UIButtonTypeCustom];
        UIImage *compassImage = [RMMapView resourceImageNamed:@"Compass.png"];
        [_compassButton setImage:compassImage forState:UIControlStateNormal];
        _compassButton.frame = CGRectMake(self.bounds.size.width - compassImage.size.width - 5, 5, compassImage.size.width, compassImage.size.height);
        _compassButton.alpha = 0;
        _compassButton.translatesAutoresizingMaskIntoConstraints = NO;
        [_compassButton addTarget:self action:@selector(tappedHeadingCompass:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_compassButton];
    }

    self.displayHeadingCalibration = YES;

    _mapTransform = CGAffineTransformIdentity;
    _annotationTransform = CATransform3DIdentity;

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleMemoryWarningNotification:)
                                                 name:UIApplicationDidReceiveMemoryWarningNotification
                                               object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleWillChangeOrientationNotification:)
                                                 name:UIApplicationWillChangeStatusBarOrientationNotification
                                               object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleDidChangeOrientationNotification:)
                                                 name:UIApplicationDidChangeStatusBarOrientationNotification
                                               object:nil];

    RMLog(@"Map initialised. tileSource:%@, minZoom:%f, maxZoom:%f, zoom:%f at {%f,%f}", newTilesource, self.minZoom, self.maxZoom, self.zoom, initialCenterCoordinate.longitude, initialCenterCoordinate.latitude);

    [self setNeedsUpdateConstraints];
}

- (id)initWithFrame:(CGRect)frame
{
    return [self initWithFrame:frame andTilesource:[RMMapBoxSource new]];
}

- (id)initWithFrame:(CGRect)frame andTilesource:(id <RMTileSource>)newTilesource
{
	return [self initWithFrame:frame
                 andTilesource:newTilesource
              centerCoordinate:CLLocationCoordinate2DMake(kDefaultInitialLatitude, kDefaultInitialLongitude)
                     zoomLevel:kDefaultInitialZoomLevel
                  maxZoomLevel:kDefaultMaximumZoomLevel
                  minZoomLevel:kDefaultMinimumZoomLevel
               backgroundImage:nil];
}

- (id)initWithFrame:(CGRect)frame
      andTilesource:(id <RMTileSource>)newTilesource
   centerCoordinate:(CLLocationCoordinate2D)initialCenterCoordinate
          zoomLevel:(float)initialZoomLevel
       maxZoomLevel:(float)maxZoomLevel
       minZoomLevel:(float)minZoomLevel
    backgroundImage:(UIImage *)backgroundImage
{
    if (!newTilesource || !(self = [super initWithFrame:frame]))
        return nil;

    [self performInitializationWithTilesource:newTilesource
                             centerCoordinate:initialCenterCoordinate
                                    zoomLevel:initialZoomLevel
                                 maxZoomLevel:maxZoomLevel
                                 minZoomLevel:minZoomLevel
                              backgroundImage:backgroundImage];

    return self;
}

- (void)setFrame:(CGRect)frame
{
    CGRect r = self.frame;
    [super setFrame:frame];

    // only change if the frame changes and not during initialization
    if ( ! CGRectEqualToRect(r, frame))
    {
        RMProjectedPoint centerPoint = self.centerProjectedPoint;

        CGRect bounds = CGRectMake(0, 0, frame.size.width, frame.size.height);
        _backgroundView.frame = bounds;
        _mapScrollView.frame = bounds;
        _overlayView.frame = bounds;

        [self setCenterProjectedPoint:centerPoint animated:NO];

        [self correctPositionOfAllAnnotations];

        self.minZoom = 0; // force new minZoom calculation

        if (_loadingTileView)
            _loadingTileView.mapZooming = NO;
    }
}

+ (UIImage *)resourceImageNamed:(NSString *)imageName
{
    if ( ! [[imageName pathExtension] length])
        imageName = [imageName stringByAppendingString:@".png"];

    return [UIImage imageWithContentsOfFile:[[self class] pathForBundleResourceNamed:imageName ofType:nil]];
}

+ (NSString *)pathForBundleResourceNamed:(NSString *)name ofType:(NSString *)extension
{
    NSAssert([[NSBundle mainBundle] pathForResource:@"MapBox" ofType:@"bundle"], @"Resource bundle not found in application.");

    NSString *bundlePath      = [[NSBundle mainBundle] pathForResource:@"MapBox" ofType:@"bundle"];
    NSBundle *resourcesBundle = [NSBundle bundleWithPath:bundlePath];

    return [resourcesBundle pathForResource:name ofType:extension];
}

- (void)dealloc
{
    [_moveDelegateQueue cancelAllOperations];
    [_zoomDelegateQueue cancelAllOperations];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [_mapScrollView removeObserver:self forKeyPath:@"contentOffset"];
    [_tileSourcesContainer cancelAllDownloads];
    _locationManager.delegate = nil;
    [_locationManager stopUpdatingLocation];
    [_locationManager stopUpdatingHeading];
}

- (void)didReceiveMemoryWarning
{
    LogMethod();

    [self.tileCache didReceiveMemoryWarning];
    [self.tileSourcesContainer didReceiveMemoryWarning];
}

- (void)handleMemoryWarningNotification:(NSNotification *)notification
{
	[self didReceiveMemoryWarning];
}

- (void)handleWillChangeOrientationNotification:(NSNotification *)notification
{
    // send a dummy heading update to force re-rotation
    //
    if (self.userTrackingMode == RMUserTrackingModeFollowWithHeading)
        [self locationManager:_locationManager didUpdateHeading:_locationManager.heading];

    // fix UIScrollView artifacts from rotation at minZoomScale
    //
    _rotateAtMinZoom = fabs(self.zoom - self.minZoom) < 0.1;
}

- (void)handleDidChangeOrientationNotification:(NSNotification *)notification
{
    if (_rotateAtMinZoom)
        [_mapScrollView setZoomScale:_mapScrollView.minimumZoomScale animated:YES];

    [self updateHeadingForDeviceOrientation];
}

- (void)setTopLayoutGuide:(id <UILayoutSupport>)topLayoutGuide
{
    if (RMPostVersion7 && ! [_topLayoutGuide isEqual:topLayoutGuide])
    {
        _topLayoutGuide = topLayoutGuide;

        [self setNeedsUpdateConstraints];
    }
}

- (void)setBottomLayoutGuide:(id<UILayoutSupport>)bottomLayoutGuide
{
    if (RMPostVersion7 && ! [_bottomLayoutGuide isEqual:bottomLayoutGuide])
    {
        _bottomLayoutGuide = bottomLayoutGuide;

        [self setNeedsUpdateConstraints];
    }
}

- (void)updateConstraints
{
    if (RMPostVersion7)
    {
        // compass
        //
        if (_compassButton)
        {
            for (UIView *constraintView in @[ self, self.superview ])
                for (NSLayoutConstraint *constraint in [constraintView.constraints copy])
                    if ([constraint.firstItem isEqual:_compassButton] || [constraint.secondItem isEqual:_compassButton])
                        [constraintView removeConstraint:constraint];

            if (self.topLayoutGuide)
            {
                [self.superview addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[topLayoutGuide]-5-[compass]"
                                                                                       options:0
                                                                                       metrics:nil
                                                                                         views:@{ @"topLayoutGuide" : self.topLayoutGuide,
                                                                                                  @"compass"        : _compassButton }]];
            }
            else
            {
                [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-5-[compass]"
                                                                             options:0
                                                                             metrics:nil
                                                                               views:@{ @"compass" : _compassButton }]];
            }

            [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[compass]-5-|"
                                                                         options:0
                                                                         metrics:nil
                                                                           views:@{ @"compass" : _compassButton }]];
        }
    }

    if (_logoBug)
    {
        for (UIView *constraintView in @[ self, self.superview ])
            for (NSLayoutConstraint *constraint in [constraintView.constraints copy])
                if ([constraint.firstItem isEqual:_logoBug] || [constraint.secondItem isEqual:_logoBug])
                    [constraintView removeConstraint:constraint];

        if (self.bottomLayoutGuide)
        {
            [self.superview addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[logoBug]-4-[bottomLayoutGuide]"
                                                                                   options:0
                                                                                   metrics:nil
                                                                                     views:@{ @"logoBug"           : _logoBug,
                                                                                              @"bottomLayoutGuide" : self.bottomLayoutGuide }]];
        }
        else
        {
            [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[logoBug]-4-|"
                                                                         options:0
                                                                         metrics:nil
                                                                           views:@{ @"logoBug" : _logoBug }]];
        }

        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-8-[logoBug]"
                                                                     options:0
                                                                     metrics:nil
                                                                       views:@{ @"logoBug" : _logoBug }]];
    }

    if (_attributionButton)
    {
        for (UIView *constraintView in @[ self, self.superview ])
            for (NSLayoutConstraint *constraint in [constraintView.constraints copy])
                if ([constraint.firstItem isEqual:_attributionButton] || [constraint.secondItem isEqual:_attributionButton])
                    [constraintView removeConstraint:constraint];

        if (self.bottomLayoutGuide)
        {
            [self.superview addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[attributionButton]-8-[bottomLayoutGuide]"
                                                                                   options:0
                                                                                   metrics:nil
                                                                                     views:@{ @"attributionButton" : _attributionButton,
                                                                                              @"bottomLayoutGuide" : self.bottomLayoutGuide }]];
        }
        else
        {
            [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[attributionButton]-8-|"
                                                                         options:0
                                                                         metrics:nil
                                                                           views:@{ @"attributionButton" : _attributionButton }]];
        }

        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[attributionButton]-8-|"
                                                                     options:0
                                                                     metrics:nil
                                                                       views:@{ @"attributionButton" : _attributionButton }]];
    }

    // TODO: distance scale

    [super updateConstraints];
}

- (void)layoutSubviews
{
    if ( ! _mapScrollView)
    {
        // This will happen after initWithCoder: This needs to happen here because during
        // unarchiving, the view won't have a frame yet and performInitialization...
        // needs a scroll view frame in order to calculate _metersPerPixel.
        // See https://github.com/mapbox/mapbox-ios-sdk/issues/270
        //
        [self performInitializationWithTilesource:[RMMapBoxSource new]
                                 centerCoordinate:CLLocationCoordinate2DMake(kDefaultInitialLatitude, kDefaultInitialLongitude)
                                        zoomLevel:kDefaultInitialZoomLevel
                                     maxZoomLevel:kDefaultMaximumZoomLevel
                                     minZoomLevel:kDefaultMinimumZoomLevel
                                  backgroundImage:nil];
    }

    if ( ! self.viewControllerPresentingAttribution && ! _hideAttribution)
    {
        UIResponder *responder = self;

        while ((responder = [responder nextResponder]))
        {
            if ([responder isKindOfClass:[UIViewController class]])
            {
                self.viewControllerPresentingAttribution = (UIViewController *)responder;
                break;
            }
        }
    }
    else if (self.viewControllerPresentingAttribution && _hideAttribution)
    {
        self.viewControllerPresentingAttribution = nil;
    }

    [super layoutSubviews];
}

- (void)removeFromSuperview
{
    self.viewControllerPresentingAttribution = nil;

    [super removeFromSuperview];
}

- (NSString *)description
{
	CGRect bounds = self.bounds;

	return [NSString stringWithFormat:@"MapView at {%.0f,%.0f}-{%.0fx%.0f}", bounds.origin.x, bounds.origin.y, bounds.size.width, bounds.size.height];
}

#pragma mark -
#pragma mark Delegate

- (id <RMMapViewDelegate>)delegate
{
	return _delegate;
}

- (void)setDelegate:(id <RMMapViewDelegate>)aDelegate
{
    if (_delegate == aDelegate)
        return;

    _delegate = aDelegate;

    _delegateHasBeforeMapMove = [_delegate respondsToSelector:@selector(beforeMapMove:byUser:)];
    _delegateHasAfterMapMove  = [_delegate respondsToSelector:@selector(afterMapMove:byUser:)];

    _delegateHasBeforeMapZoom = [_delegate respondsToSelector:@selector(beforeMapZoom:byUser:)];
    _delegateHasAfterMapZoom  = [_delegate respondsToSelector:@selector(afterMapZoom:byUser:)];

    _delegateHasMapViewRegionDidChange = [_delegate respondsToSelector:@selector(mapViewRegionDidChange:)];

    _delegateHasDoubleTapOnMap = [_delegate respondsToSelector:@selector(doubleTapOnMap:at:)];
    _delegateHasSingleTapOnMap = [_delegate respondsToSelector:@selector(singleTapOnMap:at:)];
    _delegateHasSingleTapTwoFingersOnMap = [_delegate respondsToSelector:@selector(singleTapTwoFingersOnMap:at:)];
    _delegateHasLongPressOnMap = [_delegate respondsToSelector:@selector(longPressOnMap:at:)];

    _delegateHasTapOnAnnotation = [_delegate respondsToSelector:@selector(tapOnAnnotation:onMap:)];
    _delegateHasDoubleTapOnAnnotation = [_delegate respondsToSelector:@selector(doubleTapOnAnnotation:onMap:)];
    _delegateHasLongPressOnAnnotation = [_delegate respondsToSelector:@selector(longPressOnAnnotation:onMap:)];
    _delegateHasTapOnCalloutAccessoryControlForAnnotation = [_delegate respondsToSelector:@selector(tapOnCalloutAccessoryControl:forAnnotation:onMap:)];
    _delegateHasTapOnLabelForAnnotation = [_delegate respondsToSelector:@selector(tapOnLabelForAnnotation:onMap:)];
    _delegateHasDoubleTapOnLabelForAnnotation = [_delegate respondsToSelector:@selector(doubleTapOnLabelForAnnotation:onMap:)];

    _delegateHasShouldDragMarker = [_delegate respondsToSelector:@selector(mapView:shouldDragAnnotation:)];
    _delegateHasDidDragMarker = [_delegate respondsToSelector:@selector(mapView:didDragAnnotation:withDelta:)];
    _delegateHasDidEndDragMarker = [_delegate respondsToSelector:@selector(mapView:didEndDragAnnotation:)];

    _delegateHasLayerForAnnotation = [_delegate respondsToSelector:@selector(mapView:layerForAnnotation:)];
    _delegateHasWillHideLayerForAnnotation = [_delegate respondsToSelector:@selector(mapView:willHideLayerForAnnotation:)];
    _delegateHasDidHideLayerForAnnotation = [_delegate respondsToSelector:@selector(mapView:didHideLayerForAnnotation:)];

    _delegateHasDidSelectAnnotation = [_delegate respondsToSelector:@selector(mapView:didSelectAnnotation:)];
    _delegateHasDidDeselectAnnotation = [_delegate respondsToSelector:@selector(mapView:didDeselectAnnotation:)];

    _delegateHasWillStartLocatingUser = [_delegate respondsToSelector:@selector(mapViewWillStartLocatingUser:)];
    _delegateHasDidStopLocatingUser = [_delegate respondsToSelector:@selector(mapViewDidStopLocatingUser:)];
    _delegateHasDidUpdateUserLocation = [_delegate respondsToSelector:@selector(mapView:didUpdateUserLocation:)];
    _delegateHasDidFailToLocateUserWithError = [_delegate respondsToSelector:@selector(mapView:didFailToLocateUserWithError:)];
    _delegateHasDidChangeUserTrackingMode = [_delegate respondsToSelector:@selector(mapView:didChangeUserTrackingMode:animated:)];
}

- (void)registerMoveEventByUser:(BOOL)wasUserEvent
{
    @synchronized (_moveDelegateQueue)
    {
        BOOL flag = wasUserEvent;

        if ([_moveDelegateQueue operationCount] == 0)
        {
            dispatch_async(dispatch_get_main_queue(), ^(void)
            {
                if (_delegateHasBeforeMapMove)
                    [_delegate beforeMapMove:self byUser:flag];
            });
        }

        [_moveDelegateQueue setSuspended:YES];

        if ([_moveDelegateQueue operationCount] == 0)
        {
            [_moveDelegateQueue addOperationWithBlock:^(void)
            {
                dispatch_async(dispatch_get_main_queue(), ^(void)
                {
                    if (_delegateHasAfterMapMove)
                        [_delegate afterMapMove:self byUser:flag];
                });
            }];
        }
    }
}

- (void)completeMoveEventAfterDelay:(NSTimeInterval)delay
{
    if ( ! delay)
        [_moveDelegateQueue setSuspended:NO];
    else
        [_moveDelegateQueue performSelector:@selector(setSuspended:) withObject:[NSNumber numberWithBool:NO] afterDelay:delay];
}

- (void)registerZoomEventByUser:(BOOL)wasUserEvent
{
    @synchronized (_zoomDelegateQueue)
    {
        BOOL flag = wasUserEvent;

        if ([_zoomDelegateQueue operationCount] == 0)
        {
            dispatch_async(dispatch_get_main_queue(), ^(void)
            {
                if (_delegateHasBeforeMapZoom)
                    [_delegate beforeMapZoom:self byUser:flag];
            });
        }

        [_zoomDelegateQueue setSuspended:YES];

        if ([_zoomDelegateQueue operationCount] == 0)
        {
            [_zoomDelegateQueue addOperationWithBlock:^(void)
            {
                dispatch_async(dispatch_get_main_queue(), ^(void)
                {
                    if (_delegateHasAfterMapZoom)
                        [_delegate afterMapZoom:self byUser:flag];
                });
            }];
        }
    }
}

- (void)completeZoomEventAfterDelay:(NSTimeInterval)delay
{
    if ( ! delay)
        [_zoomDelegateQueue setSuspended:NO];
    else
        [_zoomDelegateQueue performSelector:@selector(setSuspended:) withObject:[NSNumber numberWithBool:NO] afterDelay:delay];
}

#pragma mark -
#pragma mark Bounds

- (RMProjectedRect)fitProjectedRect:(RMProjectedRect)rect1 intoRect:(RMProjectedRect)rect2
{
    if (rect1.size.width > rect2.size.width || rect1.size.height > rect2.size.height)
        return rect2;

    RMProjectedRect fittedRect = RMProjectedRectMake(0.0, 0.0, rect1.size.width, rect1.size.height);

    if (rect1.origin.x < rect2.origin.x)
        fittedRect.origin.x = rect2.origin.x;
    else if (rect1.origin.x + rect1.size.width > rect2.origin.x + rect2.size.width)
        fittedRect.origin.x = (rect2.origin.x + rect2.size.width) - rect1.size.width;
    else
        fittedRect.origin.x = rect1.origin.x;

    if (rect1.origin.y < rect2.origin.y)
        fittedRect.origin.y = rect2.origin.y;
    else if (rect1.origin.y + rect1.size.height > rect2.origin.y + rect2.size.height)
        fittedRect.origin.y = (rect2.origin.y + rect2.size.height) - rect1.size.height;
    else
        fittedRect.origin.y = rect1.origin.y;

    return fittedRect;
}

- (RMProjectedRect)projectedRectFromLatitudeLongitudeBounds:(RMSphericalTrapezium)bounds
{
    CLLocationCoordinate2D southWest = bounds.southWest;
    CLLocationCoordinate2D northEast = bounds.northEast;
    CLLocationCoordinate2D midpoint = {
        .latitude = (northEast.latitude + southWest.latitude) / 2,
        .longitude = (northEast.longitude + southWest.longitude) / 2
    };

    RMProjectedPoint myOrigin = [_projection coordinateToProjectedPoint:midpoint];
    RMProjectedPoint southWestPoint = [_projection coordinateToProjectedPoint:southWest];
    RMProjectedPoint northEastPoint = [_projection coordinateToProjectedPoint:northEast];
    RMProjectedPoint myPoint = {
        .x = northEastPoint.x - southWestPoint.x,
        .y = northEastPoint.y - southWestPoint.y
    };

    // Create the new zoom layout
    RMProjectedRect zoomRect;

    // Default is with scale = 2.0 * mercators/pixel
    zoomRect.size.width = self.bounds.size.width * 2.0;
    zoomRect.size.height = self.bounds.size.height * 2.0;

    if ((myPoint.x / self.bounds.size.width) < (myPoint.y / self.bounds.size.height))
    {
        if ((myPoint.y / self.bounds.size.height) > 1)
        {
            zoomRect.size.width = self.bounds.size.width * (myPoint.y / self.bounds.size.height);
            zoomRect.size.height = self.bounds.size.height * (myPoint.y / self.bounds.size.height);
        }
    }
    else
    {
        if ((myPoint.x / self.bounds.size.width) > 1)
        {
            zoomRect.size.width = self.bounds.size.width * (myPoint.x / self.bounds.size.width);
            zoomRect.size.height = self.bounds.size.height * (myPoint.x / self.bounds.size.width);
        }
    }

    myOrigin.x = myOrigin.x - (zoomRect.size.width / 2);
    myOrigin.y = myOrigin.y - (zoomRect.size.height / 2);

    RMLog(@"Origin is calculated at: %f, %f", [_projection projectedPointToCoordinate:myOrigin].longitude, [_projection projectedPointToCoordinate:myOrigin].latitude);

    zoomRect.origin = myOrigin;

//    RMLog(@"Origin: x=%f, y=%f, w=%f, h=%f", zoomRect.origin.easting, zoomRect.origin.northing, zoomRect.size.width, zoomRect.size.height);

    return zoomRect;
}

- (BOOL)tileSourceBoundsContainProjectedPoint:(RMProjectedPoint)point
{
    RMSphericalTrapezium bounds = [self.tileSourcesContainer latitudeLongitudeBoundingBox];

    if (bounds.northEast.latitude == 90.0 && bounds.northEast.longitude == 180.0 &&
        bounds.southWest.latitude == -90.0 && bounds.southWest.longitude == -180.0)
    {
        return YES;
    }

    return RMProjectedRectContainsProjectedPoint(_constrainingProjectedBounds, point);
}

- (BOOL)tileSourceBoundsContainScreenPoint:(CGPoint)pixelCoordinate
{
    RMProjectedPoint projectedPoint = [self pixelToProjectedPoint:pixelCoordinate];

    return [self tileSourceBoundsContainProjectedPoint:projectedPoint];
}

// ===

- (void)setConstraintsSouthWest:(CLLocationCoordinate2D)southWest northEast:(CLLocationCoordinate2D)northEast
{
    RMProjectedPoint projectedSouthWest = [_projection coordinateToProjectedPoint:southWest];
    RMProjectedPoint projectedNorthEast = [_projection coordinateToProjectedPoint:northEast];

    [self setProjectedConstraintsSouthWest:projectedSouthWest northEast:projectedNorthEast];
}

- (void)setProjectedConstraintsSouthWest:(RMProjectedPoint)southWest northEast:(RMProjectedPoint)northEast
{
    _constrainMovement = _constrainMovementByUser = YES;
    _constrainingProjectedBounds = RMProjectedRectMake(southWest.x, southWest.y, northEast.x - southWest.x, northEast.y - southWest.y);
    _constrainingProjectedBoundsByUser = RMProjectedRectMake(southWest.x, southWest.y, northEast.x - southWest.x, northEast.y - southWest.y);
}

- (void)setTileSourcesConstraintsFromLatitudeLongitudeBoundingBox:(RMSphericalTrapezium)bounds
{
    BOOL tileSourcesConstrainMovement = !(bounds.northEast.latitude == 90.0 && bounds.northEast.longitude == 180.0 && bounds.southWest.latitude == -90.0 && bounds.southWest.longitude == -180.0);

    if (tileSourcesConstrainMovement)
    {
        _constrainMovement = YES;
        RMProjectedRect tileSourcesConstrainingProjectedBounds = [self projectedRectFromLatitudeLongitudeBounds:bounds];

        if (_constrainMovementByUser)
        {
            _constrainingProjectedBounds = RMProjectedRectIntersection(_constrainingProjectedBoundsByUser, tileSourcesConstrainingProjectedBounds);

            if (RMProjectedRectIsZero(_constrainingProjectedBounds))
                RMLog(@"The constraining bounds from tilesources and user don't intersect!");
        }
        else
            _constrainingProjectedBounds = tileSourcesConstrainingProjectedBounds;
    }
    else if (_constrainMovementByUser)
    {
        _constrainingProjectedBounds = _constrainingProjectedBoundsByUser;
    }
    else
    {
        _constrainingProjectedBounds = _projection.planetBounds;
    }
}

#pragma mark -
#pragma mark Movement

- (CLLocationCoordinate2D)centerCoordinate
{
    return [_projection projectedPointToCoordinate:[self centerProjectedPoint]];
}

- (void)setCenterCoordinate:(CLLocationCoordinate2D)centerCoordinate
{
    [self setCenterProjectedPoint:[_projection coordinateToProjectedPoint:centerCoordinate]];
}

- (void)setCenterCoordinate:(CLLocationCoordinate2D)centerCoordinate animated:(BOOL)animated
{
    [self setCenterProjectedPoint:[_projection coordinateToProjectedPoint:centerCoordinate] animated:animated];
}

// ===

- (RMProjectedPoint)centerProjectedPoint
{
    CGPoint center = CGPointMake(_mapScrollView.contentOffset.x + _mapScrollView.bounds.size.width/2.0, _mapScrollView.contentSize.height - (_mapScrollView.contentOffset.y + _mapScrollView.bounds.size.height/2.0));

    RMProjectedRect planetBounds = _projection.planetBounds;
    RMProjectedPoint normalizedProjectedPoint;
    normalizedProjectedPoint.x = (center.x * _metersPerPixel) - fabs(planetBounds.origin.x);
    normalizedProjectedPoint.y = (center.y * _metersPerPixel) - fabs(planetBounds.origin.y);

//    RMLog(@"centerProjectedPoint: {%f,%f}", normalizedProjectedPoint.x, normalizedProjectedPoint.y);

    return normalizedProjectedPoint;
}

- (void)setCenterProjectedPoint:(RMProjectedPoint)centerProjectedPoint
{
    [self setCenterProjectedPoint:centerProjectedPoint animated:YES];
}

- (void)setCenterProjectedPoint:(RMProjectedPoint)centerProjectedPoint animated:(BOOL)animated
{
    if (RMProjectedPointEqualToProjectedPoint(centerProjectedPoint, [self centerProjectedPoint]))
        return;

    [self registerMoveEventByUser:NO];

//    RMLog(@"Current contentSize: {%.0f,%.0f}, zoom: %f", mapScrollView.contentSize.width, mapScrollView.contentSize.height, self.zoom);

    RMProjectedRect planetBounds = _projection.planetBounds;
	RMProjectedPoint normalizedProjectedPoint;
	normalizedProjectedPoint.x = centerProjectedPoint.x + fabs(planetBounds.origin.x);
	normalizedProjectedPoint.y = centerProjectedPoint.y + fabs(planetBounds.origin.y);

    [_mapScrollView setContentOffset:CGPointMake(normalizedProjectedPoint.x / _metersPerPixel - _mapScrollView.bounds.size.width/2.0,
                                                _mapScrollView.contentSize.height - ((normalizedProjectedPoint.y / _metersPerPixel) + _mapScrollView.bounds.size.height/2.0))
                           animated:animated];

//    RMLog(@"setMapCenterProjectedPoint: {%f,%f} -> {%.0f,%.0f}", centerProjectedPoint.x, centerProjectedPoint.y, mapScrollView.contentOffset.x, mapScrollView.contentOffset.y);

    if ( ! animated)
        [self completeMoveEventAfterDelay:0];

    [self correctPositionOfAllAnnotations];
}

// ===

- (void)moveBy:(CGSize)delta
{
    [self registerMoveEventByUser:NO];

    CGPoint contentOffset = _mapScrollView.contentOffset;
    contentOffset.x += delta.width;
    contentOffset.y += delta.height;
    _mapScrollView.contentOffset = contentOffset;

    [self completeMoveEventAfterDelay:0];
}

#pragma mark -
#pragma mark Zoom

- (RMProjectedRect)projectedBounds
{
    CGPoint bottomLeft = CGPointMake(_mapScrollView.contentOffset.x, _mapScrollView.contentSize.height - (_mapScrollView.contentOffset.y + _mapScrollView.bounds.size.height));

    RMProjectedRect planetBounds = _projection.planetBounds;
    RMProjectedRect normalizedProjectedRect;
    normalizedProjectedRect.origin.x = (bottomLeft.x * _metersPerPixel) - fabs(planetBounds.origin.x);
    normalizedProjectedRect.origin.y = (bottomLeft.y * _metersPerPixel) - fabs(planetBounds.origin.y);
    normalizedProjectedRect.size.width = _mapScrollView.bounds.size.width * _metersPerPixel;
    normalizedProjectedRect.size.height = _mapScrollView.bounds.size.height * _metersPerPixel;

    return normalizedProjectedRect;
}

- (void)setProjectedBounds:(RMProjectedRect)boundsRect
{
    [self setProjectedBounds:boundsRect animated:YES];
}

- (void)setProjectedBounds:(RMProjectedRect)boundsRect animated:(BOOL)animated
{
    if (_constrainMovement)
        boundsRect = [self fitProjectedRect:boundsRect intoRect:_constrainingProjectedBounds];

    RMProjectedRect planetBounds = _projection.planetBounds;
	RMProjectedPoint normalizedProjectedPoint;
	normalizedProjectedPoint.x = boundsRect.origin.x + fabs(planetBounds.origin.x);
	normalizedProjectedPoint.y = boundsRect.origin.y + fabs(planetBounds.origin.y);

    float zoomScale = _mapScrollView.zoomScale;
    CGRect zoomRect = CGRectMake((normalizedProjectedPoint.x / _metersPerPixel) / zoomScale,
                                 ((planetBounds.size.height - normalizedProjectedPoint.y - boundsRect.size.height) / _metersPerPixel) / zoomScale,
                                 (boundsRect.size.width / _metersPerPixel) / zoomScale,
                                 (boundsRect.size.height / _metersPerPixel) / zoomScale);
    [_mapScrollView zoomToRect:zoomRect animated:animated];
}

- (BOOL)shouldZoomToTargetZoom:(float)targetZoom withZoomFactor:(float)zoomFactor
{
    // bools for syntactical sugar to understand the logic in the if statement below
    BOOL zoomAtMax = ([self zoom] == [self maxZoom]);
    BOOL zoomAtMin = ([self zoom] == [self minZoom]);
    BOOL zoomGreaterMin = ([self zoom] > [self minZoom]);
    BOOL zoomLessMax = ([self zoom] < [self maxZoom]);

    //zooming in zoomFactor > 1
    //zooming out zoomFactor < 1
    if ((zoomGreaterMin && zoomLessMax) || (zoomAtMax && zoomFactor<1) || (zoomAtMin && zoomFactor>1))
        return YES;
    else
        return NO;
}

- (void)setZoom:(float)newZoom animated:(BOOL)animated
{
    [self setZoom:newZoom atCoordinate:self.centerCoordinate animated:animated];
}

- (void)setZoom:(float)newZoom atCoordinate:(CLLocationCoordinate2D)newCenter animated:(BOOL)animated
{
    [UIView animateWithDuration:(animated ? 0.3 : 0.0)
                          delay:0.0
                        options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationCurveEaseInOut
                     animations:^(void)
                     {
                         [self setZoom:newZoom];
                         [self setCenterCoordinate:newCenter animated:NO];

                         self.userTrackingMode = RMUserTrackingModeNone;
                     }
                     completion:nil];
}

- (void)zoomByFactor:(float)zoomFactor near:(CGPoint)pivot animated:(BOOL)animated
{
    if (![self tileSourceBoundsContainScreenPoint:pivot])
        return;

    float zoomDelta = log2f(zoomFactor);
    float targetZoom = zoomDelta + [self zoom];

    if (targetZoom == [self zoom])
        return;

    // clamp zoom to remain below or equal to maxZoom after zoomAfter will be applied
    // Set targetZoom to maxZoom so the map zooms to its maximum
    if (targetZoom > [self maxZoom])
    {
        zoomFactor = exp2f([self maxZoom] - [self zoom]);
        targetZoom = [self maxZoom];
    }

    // clamp zoom to remain above or equal to minZoom after zoomAfter will be applied
    // Set targetZoom to minZoom so the map zooms to its maximum
    if (targetZoom < [self minZoom])
    {
        zoomFactor = 1/exp2f([self zoom] - [self minZoom]);
        targetZoom = [self minZoom];
    }

    if ([self shouldZoomToTargetZoom:targetZoom withZoomFactor:zoomFactor])
    {
        float zoomScale = _mapScrollView.zoomScale;
        CGSize newZoomSize = CGSizeMake(_mapScrollView.bounds.size.width / zoomFactor,
                                        _mapScrollView.bounds.size.height / zoomFactor);
        CGFloat factorX = pivot.x / _mapScrollView.bounds.size.width,
                factorY = pivot.y / _mapScrollView.bounds.size.height;
        CGRect zoomRect = CGRectMake(((_mapScrollView.contentOffset.x + pivot.x) - (newZoomSize.width * factorX)) / zoomScale,
                                     ((_mapScrollView.contentOffset.y + pivot.y) - (newZoomSize.height * factorY)) / zoomScale,
                                     newZoomSize.width / zoomScale,
                                     newZoomSize.height / zoomScale);
        [_mapScrollView zoomToRect:zoomRect animated:animated];
    }
    else
    {
        if ([self zoom] > [self maxZoom])
            [self setZoom:[self maxZoom]];
        if ([self zoom] < [self minZoom])
            [self setZoom:[self minZoom]];
    }
}

- (float)nextNativeZoomFactor
{
    float newZoom = fminf(floorf([self zoom] + 1.0), [self maxZoom]);

    return exp2f(newZoom - [self zoom]);
}

- (float)previousNativeZoomFactor
{
    float newZoom = fmaxf(floorf([self zoom] - 1.0), [self minZoom]);

    return exp2f(newZoom - [self zoom]);
}

- (void)zoomInToNextNativeZoomAt:(CGPoint)pivot
{
    [self zoomInToNextNativeZoomAt:pivot animated:NO];
}

- (void)zoomInToNextNativeZoomAt:(CGPoint)pivot animated:(BOOL)animated
{
    if (self.userTrackingMode != RMUserTrackingModeNone && ! CGPointEqualToPoint(pivot, [self coordinateToPixel:self.userLocation.location.coordinate]))
        self.userTrackingMode = RMUserTrackingModeNone;
    
    // Calculate rounded zoom
    float newZoom = fmin(ceilf([self zoom]) + 1.0, [self maxZoom]);

    float factor = exp2f(newZoom - [self zoom]);

    if (factor > 2.25)
    {
        newZoom = fmin(ceilf([self zoom]), [self maxZoom]);
        factor = exp2f(newZoom - [self zoom]);
    }

//    RMLog(@"zoom in from:%f to:%f by factor:%f around {%f,%f}", [self zoom], newZoom, factor, pivot.x, pivot.y);
    [self zoomByFactor:factor near:pivot animated:animated];
}

- (void)zoomOutToNextNativeZoomAt:(CGPoint)pivot
{
    [self zoomOutToNextNativeZoomAt:pivot animated:NO];
}

- (void)zoomOutToNextNativeZoomAt:(CGPoint)pivot animated:(BOOL) animated
{
    // Calculate rounded zoom
    float newZoom = fmax(floorf([self zoom]), [self minZoom]);

    float factor = exp2f(newZoom - [self zoom]);

    if (factor > 0.75)
    {
        newZoom = fmax(floorf([self zoom]) - 1.0, [self minZoom]);
        factor = exp2f(newZoom - [self zoom]);
    }

//    RMLog(@"zoom out from:%f to:%f by factor:%f around {%f,%f}", [self zoom], newZoom, factor, pivot.x, pivot.y);
    [self zoomByFactor:factor near:pivot animated:animated];
}

#pragma mark -
#pragma mark Zoom With Bounds

- (void)zoomWithLatitudeLongitudeBoundsSouthWest:(CLLocationCoordinate2D)southWest northEast:(CLLocationCoordinate2D)northEast animated:(BOOL)animated
{
    if (northEast.latitude == southWest.latitude && northEast.longitude == southWest.longitude) // There are no bounds, probably only one marker.
    {
        RMProjectedRect zoomRect;
        RMProjectedPoint myOrigin = [_projection coordinateToProjectedPoint:southWest];

        // Default is with scale = 2.0 * mercators/pixel
        zoomRect.size.width = [self bounds].size.width * 2.0;
        zoomRect.size.height = [self bounds].size.height * 2.0;
        myOrigin.x = myOrigin.x - (zoomRect.size.width / 2.0);
        myOrigin.y = myOrigin.y - (zoomRect.size.height / 2.0);
        zoomRect.origin = myOrigin;

        [self setProjectedBounds:zoomRect animated:animated];
    }
    else
    {
        // Convert northEast/southWest into RMMercatorRect and call zoomWithBounds
        CLLocationCoordinate2D midpoint = {
            .latitude = (northEast.latitude + southWest.latitude) / 2,
            .longitude = (northEast.longitude + southWest.longitude) / 2
        };

        RMProjectedPoint myOrigin = [_projection coordinateToProjectedPoint:midpoint];
        RMProjectedPoint southWestPoint = [_projection coordinateToProjectedPoint:southWest];
        RMProjectedPoint northEastPoint = [_projection coordinateToProjectedPoint:northEast];
        RMProjectedPoint myPoint = {
            .x = northEastPoint.x - southWestPoint.x,
            .y = northEastPoint.y - southWestPoint.y
        };

		// Create the new zoom layout
        RMProjectedRect zoomRect;

        // Default is with scale = 2.0 * mercators/pixel
        zoomRect.size.width = self.bounds.size.width * 2.0;
        zoomRect.size.height = self.bounds.size.height * 2.0;

        if ((myPoint.x / self.bounds.size.width) < (myPoint.y / self.bounds.size.height))
        {
            if ((myPoint.y / self.bounds.size.height) > 1)
            {
                zoomRect.size.width = self.bounds.size.width * (myPoint.y / self.bounds.size.height);
                zoomRect.size.height = self.bounds.size.height * (myPoint.y / self.bounds.size.height);
            }
        }
        else
        {
            if ((myPoint.x / self.bounds.size.width) > 1)
            {
                zoomRect.size.width = self.bounds.size.width * (myPoint.x / self.bounds.size.width);
                zoomRect.size.height = self.bounds.size.height * (myPoint.x / self.bounds.size.width);
            }
        }

        myOrigin.x = myOrigin.x - (zoomRect.size.width / 2);
        myOrigin.y = myOrigin.y - (zoomRect.size.height / 2);
        zoomRect.origin = myOrigin;

        [self setProjectedBounds:zoomRect animated:animated];
    }
}

#pragma mark -
#pragma mark Cache

- (void)removeAllCachedImages
{
    [self.tileCache removeAllCachedImages];
}

#pragma mark -
#pragma mark MapView (ScrollView)

- (void)createMapView
{
    [_tileSourcesContainer cancelAllDownloads];

    [_overlayView removeFromSuperview];  _overlayView = nil;

    for (__strong RMMapTiledLayerView *tiledLayerView in _tiledLayersSuperview.subviews)
    {
        tiledLayerView.layer.contents = nil;
        [tiledLayerView removeFromSuperview];  tiledLayerView = nil;
    }

    [_tiledLayersSuperview removeFromSuperview];  _tiledLayersSuperview = nil;

    [_mapScrollView removeObserver:self forKeyPath:@"contentOffset"];
    [_mapScrollView removeFromSuperview];  _mapScrollView = nil;

    _mapScrollViewIsZooming = NO;

    int tileSideLength = [_tileSourcesContainer tileSideLength];
    CGSize contentSize = CGSizeMake(tileSideLength, tileSideLength); // zoom level 1

    _mapScrollView = [[RMMapScrollView alloc] initWithFrame:self.bounds];
    _mapScrollView.delegate = self;
    _mapScrollView.opaque = NO;
    _mapScrollView.backgroundColor = [UIColor clearColor];
    _mapScrollView.showsVerticalScrollIndicator = NO;
    _mapScrollView.showsHorizontalScrollIndicator = NO;
    _mapScrollView.scrollsToTop = NO;
    _mapScrollView.scrollEnabled = _draggingEnabled;
    _mapScrollView.bounces = _bouncingEnabled;
    _mapScrollView.bouncesZoom = _bouncingEnabled;
    _mapScrollView.contentSize = contentSize;
    _mapScrollView.minimumZoomScale = exp2f([self minZoom]);
    _mapScrollView.maximumZoomScale = exp2f([self maxZoom]);
    _mapScrollView.contentOffset = CGPointMake(0.0, 0.0);
    _mapScrollView.clipsToBounds = NO;

    _tiledLayersSuperview = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, contentSize.width, contentSize.height)];
    _tiledLayersSuperview.userInteractionEnabled = NO;

    for (id <RMTileSource> tileSource in _tileSourcesContainer.tileSources)
    {
        RMMapTiledLayerView *tiledLayerView = [[RMMapTiledLayerView alloc] initWithFrame:CGRectMake(0.0, 0.0, contentSize.width, contentSize.height) mapView:self forTileSource:tileSource];

        ((CATiledLayer *)tiledLayerView.layer).tileSize = CGSizeMake(tileSideLength, tileSideLength);

        [_tiledLayersSuperview addSubview:tiledLayerView];
    }

    [_mapScrollView addSubview:_tiledLayersSuperview];

    _lastZoom = [self zoom];
    _lastContentOffset = _mapScrollView.contentOffset;
    _accumulatedDelta = CGPointMake(0.0, 0.0);
    _lastContentSize = _mapScrollView.contentSize;

    [_mapScrollView addObserver:self forKeyPath:@"contentOffset" options:(NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld) context:NULL];
    _mapScrollView.mapScrollViewDelegate = self;

    _mapScrollView.zoomScale = exp2f([self zoom]);
    [self setDecelerationMode:_decelerationMode];

    if (_backgroundView)
        [self insertSubview:_mapScrollView aboveSubview:_backgroundView];
    else
        [self insertSubview:_mapScrollView atIndex:0];

    _overlayView = [[RMMapOverlayView alloc] initWithFrame:[self bounds]];
    _overlayView.userInteractionEnabled = NO;

    [self insertSubview:_overlayView aboveSubview:_mapScrollView];

    // add gesture recognizers

    // one finger taps
    UITapGestureRecognizer *doubleTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleDoubleTap:)];
    doubleTapRecognizer.numberOfTouchesRequired = 1;
    doubleTapRecognizer.numberOfTapsRequired = 2;
    doubleTapRecognizer.delegate = self;

    UITapGestureRecognizer *singleTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
    singleTapRecognizer.numberOfTouchesRequired = 1;
    [singleTapRecognizer requireGestureRecognizerToFail:doubleTapRecognizer];
    singleTapRecognizer.delegate = self;

    UILongPressGestureRecognizer *longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
    longPressRecognizer.delegate = self;

    [self addGestureRecognizer:singleTapRecognizer];
    [self addGestureRecognizer:doubleTapRecognizer];
    [self addGestureRecognizer:longPressRecognizer];

    // two finger taps
    UITapGestureRecognizer *twoFingerSingleTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTwoFingerSingleTap:)];
    twoFingerSingleTapRecognizer.numberOfTouchesRequired = 2;
    twoFingerSingleTapRecognizer.delegate = self;

    [self addGestureRecognizer:twoFingerSingleTapRecognizer];

    // pan
    UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanGesture:)];
    panGestureRecognizer.minimumNumberOfTouches = 1;
    panGestureRecognizer.maximumNumberOfTouches = 1;

    // the delegate is used to decide whether a pan should be handled by this
    // recognizer or by the pan gesture recognizer of the scrollview
    panGestureRecognizer.delegate = self;

    // the pan recognizer is added to the scrollview as it competes with the
    // pan recognizer of the scrollview
    [_mapScrollView addGestureRecognizer:panGestureRecognizer];

    [_visibleAnnotations removeAllObjects];
    [self correctPositionOfAllAnnotations];
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return _tiledLayersSuperview;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self registerMoveEventByUser:YES];

    if (self.userTrackingMode != RMUserTrackingModeNone)
        self.userTrackingMode = RMUserTrackingModeNone;
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if ( ! decelerate)
        [self completeMoveEventAfterDelay:0];
}

- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
{
    if (_decelerationMode == RMMapDecelerationOff)
        [scrollView setContentOffset:scrollView.contentOffset animated:NO];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self completeMoveEventAfterDelay:0];
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    [self completeMoveEventAfterDelay:0];
}

- (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view
{
    [self registerZoomEventByUser:(scrollView.pinchGestureRecognizer.state == UIGestureRecognizerStateBegan)];

    _mapScrollViewIsZooming = YES;

    if (_loadingTileView)
        _loadingTileView.mapZooming = YES;
}

- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale
{
    [self completeMoveEventAfterDelay:0];
    [self completeZoomEventAfterDelay:0];

    _mapScrollViewIsZooming = NO;

    // slight jiggle fixes problems with UIScrollView
    // briefly allowing zoom beyond min
    //
    [self moveBy:CGSizeMake(-1, -1)];
    [self moveBy:CGSizeMake( 1,  1)];

    [self correctPositionOfAllAnnotations];

    if (_loadingTileView)
        _loadingTileView.mapZooming = NO;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (_loadingTileView)
    {
        CGSize delta = CGSizeMake(scrollView.contentOffset.x - _lastContentOffset.x, scrollView.contentOffset.y - _lastContentOffset.y);
        CGPoint newOffset = CGPointMake(_loadingTileView.contentOffset.x + delta.width, _loadingTileView.contentOffset.y + delta.height);
        _loadingTileView.contentOffset = newOffset;
    }
}

- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
    BOOL wasUserAction = (scrollView.pinchGestureRecognizer.state == UIGestureRecognizerStateChanged);

    [self registerZoomEventByUser:wasUserAction];

    if (self.userTrackingMode != RMUserTrackingModeNone && wasUserAction)
        self.userTrackingMode = RMUserTrackingModeNone;
    
    [self correctPositionOfAllAnnotations];

    if (_zoom < 3 && self.userTrackingMode == RMUserTrackingModeFollowWithHeading)
        self.userTrackingMode = RMUserTrackingModeFollow;
}

// Detect dragging/zooming

- (void)scrollView:(RMMapScrollView *)aScrollView correctedContentOffset:(inout CGPoint *)aContentOffset
{
    if ( ! _constrainMovement)
        return;

    if (CGPointEqualToPoint(_lastContentOffset, *aContentOffset))
        return;

    // The first offset during zooming out (animated) is always garbage
    if (_mapScrollViewIsZooming == YES &&
        _mapScrollView.zooming == NO &&
        _lastContentSize.width > _mapScrollView.contentSize.width &&
        ((*aContentOffset).y - _lastContentOffset.y) == 0.0)
    {
        return;
    }

    RMProjectedRect planetBounds = _projection.planetBounds;
    double currentMetersPerPixel = planetBounds.size.width / aScrollView.contentSize.width;

    CGPoint bottomLeft = CGPointMake((*aContentOffset).x,
                                     aScrollView.contentSize.height - ((*aContentOffset).y + aScrollView.bounds.size.height));

    RMProjectedRect normalizedProjectedRect;
    normalizedProjectedRect.origin.x = (bottomLeft.x * currentMetersPerPixel) - fabs(planetBounds.origin.x);
    normalizedProjectedRect.origin.y = (bottomLeft.y * currentMetersPerPixel) - fabs(planetBounds.origin.y);
    normalizedProjectedRect.size.width = aScrollView.bounds.size.width * currentMetersPerPixel;
    normalizedProjectedRect.size.height = aScrollView.bounds.size.height * currentMetersPerPixel;

    if (RMProjectedRectContainsProjectedRect(_constrainingProjectedBounds, normalizedProjectedRect))
        return;

    RMProjectedRect fittedProjectedRect = [self fitProjectedRect:normalizedProjectedRect intoRect:_constrainingProjectedBounds];

    RMProjectedPoint normalizedProjectedPoint;
	normalizedProjectedPoint.x = fittedProjectedRect.origin.x + fabs(planetBounds.origin.x);
	normalizedProjectedPoint.y = fittedProjectedRect.origin.y + fabs(planetBounds.origin.y);

    CGPoint correctedContentOffset = CGPointMake(normalizedProjectedPoint.x / currentMetersPerPixel,
                                                 aScrollView.contentSize.height - ((normalizedProjectedPoint.y / currentMetersPerPixel) + aScrollView.bounds.size.height));
    *aContentOffset = correctedContentOffset;
}

- (void)scrollView:(RMMapScrollView *)aScrollView correctedContentSize:(inout CGSize *)aContentSize
{
    if ( ! _constrainMovement)
        return;

    RMProjectedRect planetBounds = _projection.planetBounds;
    double currentMetersPerPixel = planetBounds.size.width / (*aContentSize).width;

    RMProjectedSize projectedSize;
    projectedSize.width = aScrollView.bounds.size.width * currentMetersPerPixel;
    projectedSize.height = aScrollView.bounds.size.height * currentMetersPerPixel;

    if (RMProjectedSizeContainsProjectedSize(_constrainingProjectedBounds.size, projectedSize))
        return;

    CGFloat factor = 1.0;
    if (projectedSize.width > _constrainingProjectedBounds.size.width)
        factor = (projectedSize.width / _constrainingProjectedBounds.size.width);
    else
        factor = (projectedSize.height / _constrainingProjectedBounds.size.height);

    *aContentSize = CGSizeMake((*aContentSize).width * factor, (*aContentSize).height * factor);
}

- (void)observeValueForKeyPath:(NSString *)aKeyPath ofObject:(id)anObject change:(NSDictionary *)change context:(void *)context
{
    NSValue *oldValue = [change objectForKey:NSKeyValueChangeOldKey],
            *newValue = [change objectForKey:NSKeyValueChangeNewKey];

    CGPoint oldContentOffset = [oldValue CGPointValue],
            newContentOffset = [newValue CGPointValue];

    if (CGPointEqualToPoint(oldContentOffset, newContentOffset))
        return;

    // The first offset during zooming out (animated) is always garbage
    if (_mapScrollViewIsZooming == YES &&
        _mapScrollView.zooming == NO &&
        _lastContentSize.width > _mapScrollView.contentSize.width &&
        (newContentOffset.y - oldContentOffset.y) == 0.0)
    {
        _lastContentOffset = _mapScrollView.contentOffset;
        _lastContentSize = _mapScrollView.contentSize;

        return;
    }

//    RMLog(@"contentOffset: {%.0f,%.0f} -> {%.1f,%.1f} (%.0f,%.0f)", oldContentOffset.x, oldContentOffset.y, newContentOffset.x, newContentOffset.y, newContentOffset.x - oldContentOffset.x, newContentOffset.y - oldContentOffset.y);
//    RMLog(@"contentSize: {%.0f,%.0f} -> {%.0f,%.0f}", _lastContentSize.width, _lastContentSize.height, mapScrollView.contentSize.width, mapScrollView.contentSize.height);
//    RMLog(@"isZooming: %d, scrollview.zooming: %d", _mapScrollViewIsZooming, mapScrollView.zooming);

    RMProjectedRect planetBounds = _projection.planetBounds;
    _metersPerPixel = planetBounds.size.width / _mapScrollView.contentSize.width;

    _zoom = log2f(_mapScrollView.zoomScale);
    _zoom = (_zoom > _maxZoom) ? _maxZoom : _zoom;
    _zoom = (_zoom < _minZoom) ? _minZoom : _zoom;

    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(correctPositionOfAllAnnotations) object:nil];

    if (_zoom == _lastZoom)
    {
        CGPoint contentOffset = _mapScrollView.contentOffset;
        CGPoint delta = CGPointMake(_lastContentOffset.x - contentOffset.x, _lastContentOffset.y - contentOffset.y);
        _accumulatedDelta.x += delta.x;
        _accumulatedDelta.y += delta.y;

        if (fabsf(_accumulatedDelta.x) < kZoomRectPixelBuffer && fabsf(_accumulatedDelta.y) < kZoomRectPixelBuffer)
        {
            [_overlayView moveLayersBy:_accumulatedDelta];
            [self performSelector:@selector(correctPositionOfAllAnnotations) withObject:nil afterDelay:0.1];
        }
        else
        {
            if (_mapScrollViewIsZooming)
                [self correctPositionOfAllAnnotationsIncludingInvisibles:NO animated:YES];
            else
                [self correctPositionOfAllAnnotations];
        }
    }
    else
    {
        [self correctPositionOfAllAnnotationsIncludingInvisibles:NO animated:(_mapScrollViewIsZooming && !_mapScrollView.zooming)];

        if (_currentAnnotation && ! [_currentAnnotation isKindOfClass:[RMMarker class]])
        {
            // adjust shape annotation callouts for frame changes during zoom
            //
            _currentCallout.delegate = nil;

            [_currentCallout presentCalloutFromRect:_currentAnnotation.layer.bounds
                                            inLayer:_currentAnnotation.layer
                                 constrainedToLayer:self.layer
                           permittedArrowDirections:SMCalloutArrowDirectionDown
                                           animated:NO];

            _currentCallout.delegate = self;
        }

        _lastZoom = _zoom;
    }

    _lastContentOffset = _mapScrollView.contentOffset;
    _lastContentSize = _mapScrollView.contentSize;

    if (_delegateHasMapViewRegionDidChange)
        [_delegate mapViewRegionDidChange:self];
}

#pragma mark - Gesture Recognizers and event handling

- (RMAnnotation *)findAnnotationInLayer:(CALayer *)layer
{
    if ([layer respondsToSelector:@selector(annotation)])
        return [((RMMarker *)layer) annotation];

    CALayer *superlayer = [layer superlayer];

    if (superlayer != nil && [superlayer respondsToSelector:@selector(annotation)])
        return [((RMMarker *)superlayer) annotation];
    else if ([superlayer superlayer] != nil && [[superlayer superlayer] respondsToSelector:@selector(annotation)])
        return [((RMMarker *)[superlayer superlayer]) annotation];

    return nil;
}

- (void)singleTapAtPoint:(CGPoint)aPoint
{
    if (_delegateHasSingleTapOnMap)
        [_delegate singleTapOnMap:self at:aPoint];
}

- (void)handleSingleTap:(UIGestureRecognizer *)recognizer
{
    CALayer *hit = [_overlayView overlayHitTest:[recognizer locationInView:self]];

    if (_currentAnnotation && ! [hit isEqual:_currentAnnotation.layer])
    {
        [self deselectAnnotation:_currentAnnotation animated:( ! [hit isKindOfClass:[RMMarker class]])];
    }

    if ( ! hit)
    {
        [self singleTapAtPoint:[recognizer locationInView:self]];
        return;
    }

    CALayer *superlayer = [hit superlayer];

    // See if tap was on an annotation layer or marker label and send delegate protocol method
    if ([hit isKindOfClass:[RMMapLayer class]])
    {
        [self tapOnAnnotation:[((RMMapLayer *)hit) annotation] atPoint:[recognizer locationInView:self]];
    }
    else if (superlayer != nil && [superlayer isKindOfClass:[RMMarker class]])
    {
        [self tapOnLabelForAnnotation:[((RMMarker *)superlayer) annotation] atPoint:[recognizer locationInView:self]];
    }
    else if ([superlayer superlayer] != nil && [[superlayer superlayer] isKindOfClass:[RMMarker class]])
    {
        [self tapOnLabelForAnnotation:[((RMMarker *)[superlayer superlayer]) annotation] atPoint:[recognizer locationInView:self]];
    }
    else
    {
        [self singleTapAtPoint:[recognizer locationInView:self]];
    }
}

- (void)doubleTapAtPoint:(CGPoint)aPoint
{
    if (self.zoom < self.maxZoom)
    {
        [self registerZoomEventByUser:YES];

        if (self.zoomingInPivotsAroundCenter)
        {
            [self zoomInToNextNativeZoomAt:[self convertPoint:self.center fromView:self.superview] animated:YES];
        }
        else if (self.userTrackingMode != RMUserTrackingModeNone && fabsf(aPoint.x - [self coordinateToPixel:self.userLocation.location.coordinate].x) < 75 && fabsf(aPoint.y - [self coordinateToPixel:self.userLocation.location.coordinate].y) < 75)
        {
            [self zoomInToNextNativeZoomAt:[self coordinateToPixel:self.userLocation.location.coordinate] animated:YES];
        }
        else
        {
            [self registerMoveEventByUser:YES];

            [self zoomInToNextNativeZoomAt:aPoint animated:YES];
        }
    }

    if (_delegateHasDoubleTapOnMap)
        [_delegate doubleTapOnMap:self at:aPoint];
}

- (void)handleDoubleTap:(UIGestureRecognizer *)recognizer
{
    CALayer *hit = [_overlayView overlayHitTest:[recognizer locationInView:self]];

    if ( ! hit)
    {
        [self doubleTapAtPoint:[recognizer locationInView:self]];
        return;
    }

    CALayer *superlayer = [hit superlayer];

    // See if tap was on a marker or marker label and send delegate protocol method
    if ([hit isKindOfClass:[RMMarker class]])
    {
        [self doubleTapOnAnnotation:[((RMMarker *)hit) annotation] atPoint:[recognizer locationInView:self]];
    }
    else if (superlayer != nil && [superlayer isKindOfClass:[RMMarker class]])
    {
        [self doubleTapOnLabelForAnnotation:[((RMMarker *)superlayer) annotation] atPoint:[recognizer locationInView:self]];
    }
    else if ([superlayer superlayer] != nil && [[superlayer superlayer] isKindOfClass:[RMMarker class]])
    {
        [self doubleTapOnLabelForAnnotation:[((RMMarker *)[superlayer superlayer]) annotation] atPoint:[recognizer locationInView:self]];
    }
    else
    {
        [self doubleTapAtPoint:[recognizer locationInView:self]];
    }
}

- (void)handleTwoFingerSingleTap:(UIGestureRecognizer *)recognizer
{
    if (self.zoom > self.minZoom)
    {
        [self registerZoomEventByUser:YES];

        CGPoint centerPoint = [self convertPoint:self.center fromView:self.superview];

        if (self.userTrackingMode != RMUserTrackingModeNone)
            centerPoint = [self coordinateToPixel:self.userLocation.location.coordinate];

        [self zoomOutToNextNativeZoomAt:centerPoint animated:YES];
    }

    if (_delegateHasSingleTapTwoFingersOnMap)
        [_delegate singleTapTwoFingersOnMap:self at:[recognizer locationInView:self]];
}

- (void)handleLongPress:(UILongPressGestureRecognizer *)recognizer
{
    if (recognizer.state != UIGestureRecognizerStateBegan)
        return;

    if ( ! _delegateHasLongPressOnMap && ! _delegateHasLongPressOnAnnotation)
        return;

    CALayer *hit = [_overlayView overlayHitTest:[recognizer locationInView:self]];

    if (_currentAnnotation && [hit isEqual:_currentAnnotation.layer])
        [self deselectAnnotation:_currentAnnotation animated:NO];

    if ([hit isKindOfClass:[RMMapLayer class]] && _delegateHasLongPressOnAnnotation)
        [_delegate longPressOnAnnotation:[((RMMapLayer *)hit) annotation] onMap:self];

    else if (_delegateHasLongPressOnMap)
        [_delegate longPressOnMap:self at:[recognizer locationInView:self]];
}

// defines when the additional pan gesture recognizer on the scroll should handle the gesture
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)recognizer
{
    if ([recognizer isKindOfClass:[UIPanGestureRecognizer class]])
    {
        // check whether our custom pan gesture recognizer should start recognizing the gesture
        CALayer *hit = [_overlayView overlayHitTest:[recognizer locationInView:_overlayView]];

        if ([hit isEqual:_overlayView.layer])
            return NO;
        
        if (!hit || ([hit respondsToSelector:@selector(draggingEnabled)] && ![(RMMarker *)hit draggingEnabled]))
            return NO;

        if ( ! [self shouldDragAnnotation:[self findAnnotationInLayer:hit]])
            return NO;
    }

    return YES;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if ([touch.view isKindOfClass:[UIControl class]])
        return NO;

    return YES;
}

- (void)handlePanGesture:(UIPanGestureRecognizer *)recognizer
{
    if (recognizer.state == UIGestureRecognizerStateBegan)
    {
        CALayer *hit = [_overlayView.layer hitTest:[recognizer locationInView:self]];

        if ( ! hit)
            return;

        if ([hit respondsToSelector:@selector(draggingEnabled)] && ![(RMMarker *)hit draggingEnabled])
            return;

        _lastDraggingTranslation = CGPointZero;
        _draggedAnnotation = [self findAnnotationInLayer:hit];
    }

    if (recognizer.state == UIGestureRecognizerStateChanged)
    {
        CGPoint translation = [recognizer translationInView:_overlayView];
        CGPoint delta = CGPointMake(_lastDraggingTranslation.x - translation.x, _lastDraggingTranslation.y - translation.y);
        _lastDraggingTranslation = translation;

        [CATransaction begin];
        [CATransaction setAnimationDuration:0];
        [self didDragAnnotation:_draggedAnnotation withDelta:delta];
        [CATransaction commit];
    }
    else if (recognizer.state == UIGestureRecognizerStateEnded)
    {
        [self didEndDragAnnotation:_draggedAnnotation];
         _draggedAnnotation = nil;
    }
}

// Overlay

- (void)tapOnAnnotation:(RMAnnotation *)anAnnotation atPoint:(CGPoint)aPoint
{
    if (anAnnotation.isEnabled && ! [anAnnotation isEqual:_currentAnnotation])
        [self selectAnnotation:anAnnotation animated:YES];

    if (_delegateHasTapOnAnnotation && anAnnotation)
    {
        [_delegate tapOnAnnotation:anAnnotation onMap:self];
    }
    else
    {
        if (_delegateHasSingleTapOnMap)
            [_delegate singleTapOnMap:self at:aPoint];
    }
}

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
    if (_currentCallout)
    {
        UIView *calloutCandidate = [_currentCallout hitTest:[_currentCallout convertPoint:point fromView:self] withEvent:event];

        if (calloutCandidate)
            return calloutCandidate;
    }

    return [super hitTest:point withEvent:event];
}

- (void)selectAnnotation:(RMAnnotation *)anAnnotation animated:(BOOL)animated
{
    if ( ! anAnnotation && _currentAnnotation)
    {
        [self deselectAnnotation:_currentAnnotation animated:animated];
    }
    else if (anAnnotation.isEnabled && ! [anAnnotation isEqual:_currentAnnotation])
    {
        [self deselectAnnotation:_currentAnnotation animated:NO];

        _currentAnnotation = anAnnotation;

        if (anAnnotation.layer.canShowCallout && anAnnotation.title)
        {
            _currentCallout = [SMCalloutView new];

            if (RMPreVersion7)
                _currentCallout.backgroundView = [SMCalloutBackgroundView systemBackgroundView];

            if (RMPostVersion7)
                _currentCallout.tintColor = self.tintColor;

            _currentCallout.title    = anAnnotation.title;
            _currentCallout.subtitle = anAnnotation.subtitle;

            _currentCallout.calloutOffset = anAnnotation.layer.calloutOffset;

            if (anAnnotation.layer.leftCalloutAccessoryView)
            {
                if ([anAnnotation.layer.leftCalloutAccessoryView isKindOfClass:[UIControl class]])
                    [anAnnotation.layer.leftCalloutAccessoryView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapOnCalloutAccessoryWithGestureRecognizer:)]];

                _currentCallout.leftAccessoryView = anAnnotation.layer.leftCalloutAccessoryView;
            }

            if (anAnnotation.layer.rightCalloutAccessoryView)
            {
                if ([anAnnotation.layer.rightCalloutAccessoryView isKindOfClass:[UIControl class]])
                    [anAnnotation.layer.rightCalloutAccessoryView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapOnCalloutAccessoryWithGestureRecognizer:)]];

                _currentCallout.rightAccessoryView = anAnnotation.layer.rightCalloutAccessoryView;
            }

            _currentCallout.delegate = self;

            [_currentCallout presentCalloutFromRect:anAnnotation.layer.bounds
                                            inLayer:anAnnotation.layer
                                 constrainedToLayer:self.layer
                           permittedArrowDirections:SMCalloutArrowDirectionDown
                                           animated:animated];
        }

        [self correctPositionOfAllAnnotations];

        anAnnotation.layer.zPosition = _currentCallout.layer.zPosition = MAXFLOAT;

        if (_delegateHasDidSelectAnnotation)
            [_delegate mapView:self didSelectAnnotation:anAnnotation];
    }
}

- (void)deselectAnnotation:(RMAnnotation *)annotation animated:(BOOL)animated
{
    if ([annotation isEqual:_currentAnnotation])
    {
        [_currentCallout dismissCalloutAnimated:animated];

        if (animated)
            [self performSelector:@selector(correctPositionOfAllAnnotations) withObject:nil afterDelay:1.0/3.0];
        else
            [self correctPositionOfAllAnnotations];

         _currentAnnotation = nil;
         _currentCallout = nil;

        if (_delegateHasDidDeselectAnnotation)
            [_delegate mapView:self didDeselectAnnotation:annotation];
    }
}

- (void)setSelectedAnnotation:(RMAnnotation *)selectedAnnotation
{
    [self selectAnnotation:selectedAnnotation animated:YES];
}

- (RMAnnotation *)selectedAnnotation
{
    return _currentAnnotation;
}

- (NSTimeInterval)calloutView:(SMCalloutView *)calloutView delayForRepositionWithSize:(CGSize)offset
{
    [self registerMoveEventByUser:NO];

    CGPoint contentOffset = _mapScrollView.contentOffset;

    contentOffset.x -= offset.width;
    contentOffset.y -= offset.height;

    if (RMPostVersion7)
    {
        if (self.topLayoutGuide && contentOffset.y > _mapScrollView.contentOffset.y)
            contentOffset.y += offset.height;
        else if (self.topLayoutGuide && contentOffset.y < _mapScrollView.contentOffset.y)
            contentOffset.y -= self.topLayoutGuide.length;
    }

    [_mapScrollView setContentOffset:contentOffset animated:YES];

    [self completeMoveEventAfterDelay:kSMCalloutViewRepositionDelayForUIScrollView];

    return kSMCalloutViewRepositionDelayForUIScrollView;
}

- (void)tapOnCalloutAccessoryWithGestureRecognizer:(UIGestureRecognizer *)recognizer
{
    if (_delegateHasTapOnCalloutAccessoryControlForAnnotation)
        [_delegate tapOnCalloutAccessoryControl:(UIControl *)recognizer.view forAnnotation:_currentAnnotation onMap:self];
}

- (void)doubleTapOnAnnotation:(RMAnnotation *)anAnnotation atPoint:(CGPoint)aPoint
{
    if (_delegateHasDoubleTapOnAnnotation && anAnnotation)
    {
        [_delegate doubleTapOnAnnotation:anAnnotation onMap:self];
    }
    else
    {
        [self doubleTapAtPoint:aPoint];
    }
}

- (void)tapOnLabelForAnnotation:(RMAnnotation *)anAnnotation atPoint:(CGPoint)aPoint
{
    if (_delegateHasTapOnLabelForAnnotation && anAnnotation)
    {
        [_delegate tapOnLabelForAnnotation:anAnnotation onMap:self];
    }
    else if (_delegateHasTapOnAnnotation && anAnnotation)
    {
        [_delegate tapOnAnnotation:anAnnotation onMap:self];
    }
    else
    {
        if (_delegateHasSingleTapOnMap)
            [_delegate singleTapOnMap:self at:aPoint];
    }
}

- (void)doubleTapOnLabelForAnnotation:(RMAnnotation *)anAnnotation atPoint:(CGPoint)aPoint
{
    if (_delegateHasDoubleTapOnLabelForAnnotation && anAnnotation)
    {
        [_delegate doubleTapOnLabelForAnnotation:anAnnotation onMap:self];
    }
    else if (_delegateHasDoubleTapOnAnnotation && anAnnotation)
    {
        [_delegate doubleTapOnAnnotation:anAnnotation onMap:self];
    }
    else
    {
        [self doubleTapAtPoint:aPoint];
    }
}

- (BOOL)shouldDragAnnotation:(RMAnnotation *)anAnnotation
{
    if (_delegateHasShouldDragMarker)
        return [_delegate mapView:self shouldDragAnnotation:anAnnotation];
    else
        return NO;
}

- (void)didDragAnnotation:(RMAnnotation *)anAnnotation withDelta:(CGPoint)delta
{
    if (_delegateHasDidDragMarker)
        [_delegate mapView:self didDragAnnotation:anAnnotation withDelta:delta];
}

- (void)didEndDragAnnotation:(RMAnnotation *)anAnnotation
{
    if (_delegateHasDidEndDragMarker)
        [_delegate mapView:self didEndDragAnnotation:anAnnotation];
}

#pragma mark -
#pragma mark Snapshots

- (UIImage *)takeSnapshotAndIncludeOverlay:(BOOL)includeOverlay
{
    _overlayView.hidden = !includeOverlay;

    UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.opaque, [[UIScreen mainScreen] scale]);

    for (RMMapTiledLayerView *tiledLayerView in _tiledLayersSuperview.subviews)
        tiledLayerView.useSnapshotRenderer = YES;

    [self.layer renderInContext:UIGraphicsGetCurrentContext()];

    for (RMMapTiledLayerView *tiledLayerView in _tiledLayersSuperview.subviews)
        tiledLayerView.useSnapshotRenderer = NO;

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    _overlayView.hidden = NO;

    return image;
}

- (UIImage *)takeSnapshot
{
    return [self takeSnapshotAndIncludeOverlay:YES];
}

#pragma mark - TileSources

- (RMTileSourcesContainer *)tileSourcesContainer
{
    return _tileSourcesContainer;
}

- (id <RMTileSource>)tileSource
{
    NSArray *tileSources = [_tileSourcesContainer tileSources];

    if ([tileSources count] > 0)
        return [tileSources objectAtIndex:0];

    return nil;
}

- (NSArray *)tileSources
{
    return [_tileSourcesContainer tileSources];
}

- (void)setTileSource:(id <RMTileSource>)tileSource
{
    if (tileSource)
    {
        [_tileSourcesContainer removeAllTileSources];
        [self addTileSource:tileSource];
    }
}

- (void)setTileSources:(NSArray *)tileSources
{
    if ( ! [_tileSourcesContainer setTileSources:tileSources])
        return;

    RMProjectedPoint centerPoint = [self centerProjectedPoint];

    _projection = [_tileSourcesContainer projection];

    _mercatorToTileProjection = [_tileSourcesContainer mercatorToTileProjection];

    [self setTileSourcesConstraintsFromLatitudeLongitudeBoundingBox:[_tileSourcesContainer latitudeLongitudeBoundingBox]];

    [self setTileSourcesMinZoom:_tileSourcesContainer.minZoom];
    [self setTileSourcesMaxZoom:_tileSourcesContainer.maxZoom];
    [self setZoom:[self zoom]]; // setZoom clamps zoom level to min/max limits

    // Recreate the map layer
    [self createMapView];

    [self setCenterProjectedPoint:centerPoint animated:NO];
}

- (void)addTileSource:(id <RMTileSource>)tileSource
{
    [self addTileSource:tileSource atIndex:-1];
}

- (void)addTileSource:(id<RMTileSource>)newTileSource atIndex:(NSUInteger)index
{
    if ([_tileSourcesContainer.tileSources containsObject:newTileSource])
        return;

    if ( ! [_tileSourcesContainer addTileSource:newTileSource atIndex:index])
        return;

    RMProjectedPoint centerPoint = [self centerProjectedPoint];

    _projection = [_tileSourcesContainer projection];

    _mercatorToTileProjection = [_tileSourcesContainer mercatorToTileProjection];

    [self setTileSourcesConstraintsFromLatitudeLongitudeBoundingBox:[_tileSourcesContainer latitudeLongitudeBoundingBox]];

    [self setTileSourcesMinZoom:_tileSourcesContainer.minZoom];
    [self setTileSourcesMaxZoom:_tileSourcesContainer.maxZoom];
    [self setZoom:[self zoom]]; // setZoom clamps zoom level to min/max limits

    // Recreate the map layer
    NSUInteger tileSourcesContainerSize = [[_tileSourcesContainer tileSources] count];

    if (tileSourcesContainerSize == 1)
    {
        [self createMapView];
    }
    else
    {
        int tileSideLength = [_tileSourcesContainer tileSideLength];
        CGSize contentSize = CGSizeMake(tileSideLength, tileSideLength); // zoom level 1

        RMMapTiledLayerView *tiledLayerView = [[RMMapTiledLayerView alloc] initWithFrame:CGRectMake(0.0, 0.0, contentSize.width, contentSize.height) mapView:self forTileSource:newTileSource];

        ((CATiledLayer *)tiledLayerView.layer).tileSize = CGSizeMake(tileSideLength, tileSideLength);

        if (index >= [[_tileSourcesContainer tileSources] count])
            [_tiledLayersSuperview addSubview:tiledLayerView];
        else
            [_tiledLayersSuperview insertSubview:tiledLayerView atIndex:index];
    }

    [self setCenterProjectedPoint:centerPoint animated:NO];
}

- (void)removeTileSource:(id <RMTileSource>)tileSource
{
    RMProjectedPoint centerPoint = [self centerProjectedPoint];

    [_tileSourcesContainer removeTileSource:tileSource];

    if ([_tileSourcesContainer.tileSources count] == 0)
    {
        _constrainMovement = NO;
    }
    else
    {
        [self setTileSourcesConstraintsFromLatitudeLongitudeBoundingBox:[_tileSourcesContainer latitudeLongitudeBoundingBox]];
    }

    // Remove the map layer
    RMMapTiledLayerView *tileSourceTiledLayerView = nil;

    for (RMMapTiledLayerView *tiledLayerView in _tiledLayersSuperview.subviews)
    {
        if (tiledLayerView.tileSource == tileSource)
        {
            tileSourceTiledLayerView = tiledLayerView;
            break;
        }
    }

    tileSourceTiledLayerView.layer.contents = nil;
    [tileSourceTiledLayerView removeFromSuperview];  tileSourceTiledLayerView = nil;

    [self setCenterProjectedPoint:centerPoint animated:NO];
}

- (void)removeTileSourceAtIndex:(NSUInteger)index
{
    RMProjectedPoint centerPoint = [self centerProjectedPoint];

    [_tileSourcesContainer removeTileSourceAtIndex:index];

    if ([_tileSourcesContainer.tileSources count] == 0)
    {
        _constrainMovement = NO;
    }
    else
    {
        [self setTileSourcesConstraintsFromLatitudeLongitudeBoundingBox:[_tileSourcesContainer latitudeLongitudeBoundingBox]];
    }

    // Remove the map layer
    RMMapTiledLayerView *tileSourceTiledLayerView = [_tiledLayersSuperview.subviews objectAtIndex:index];

    tileSourceTiledLayerView.layer.contents = nil;
    [tileSourceTiledLayerView removeFromSuperview];  tileSourceTiledLayerView = nil;

    [self setCenterProjectedPoint:centerPoint animated:NO];
}

- (void)moveTileSourceAtIndex:(NSUInteger)fromIndex toIndex:(NSUInteger)toIndex
{
    if (fromIndex == toIndex)
        return;

    if (fromIndex >= [[_tileSourcesContainer tileSources] count])
        return;

    RMProjectedPoint centerPoint = [self centerProjectedPoint];

    [_tileSourcesContainer moveTileSourceAtIndex:fromIndex toIndex:toIndex];

    // Move the map layer
    [_tiledLayersSuperview exchangeSubviewAtIndex:fromIndex withSubviewAtIndex:toIndex];

    [self setCenterProjectedPoint:centerPoint animated:NO];
}

- (void)setHidden:(BOOL)isHidden forTileSource:(id <RMTileSource>)tileSource
{
    NSArray *tileSources = [self tileSources];

    [tileSources enumerateObjectsUsingBlock:^(id <RMTileSource> currentTileSource, NSUInteger index, BOOL *stop)
    {
        if (tileSource == currentTileSource)
        {
            [self setHidden:isHidden forTileSourceAtIndex:index];
            *stop = YES;
        }
    }];
}

- (void)setHidden:(BOOL)isHidden forTileSourceAtIndex:(NSUInteger)index
{
    if (index >= [_tiledLayersSuperview.subviews count])
        return;

    ((RMMapTiledLayerView *)[_tiledLayersSuperview.subviews objectAtIndex:index]).hidden = isHidden;
}

- (void)setAlpha:(CGFloat)alpha forTileSource:(id <RMTileSource>)tileSource
{
    NSArray *tileSources = [self tileSources];

    [tileSources enumerateObjectsUsingBlock:^(id <RMTileSource> currentTileSource, NSUInteger index, BOOL *stop)
    {
        if (tileSource == currentTileSource)
        {
            [self setAlpha:alpha forTileSourceAtIndex:index];
            *stop = YES;
        }
    }];
}

- (void)setAlpha:(CGFloat)alpha forTileSourceAtIndex:(NSUInteger)index
{
    if (index >= [_tiledLayersSuperview.subviews count])
        return;

    ((RMMapTiledLayerView *)[_tiledLayersSuperview.subviews objectAtIndex:index]).alpha = alpha;
}

- (void)reloadTileSource:(id <RMTileSource>)tileSource
{
    // Reload the map layer
    for (RMMapTiledLayerView *tiledLayerView in _tiledLayersSuperview.subviews)
    {
        if (tiledLayerView.tileSource == tileSource)
        {
//            tiledLayerView.layer.contents = nil;
            [tiledLayerView setNeedsDisplay];
            break;
        }
    }
}

- (void)reloadTileSourceAtIndex:(NSUInteger)index
{
    if (index >= [_tiledLayersSuperview.subviews count])
        return;

    // Reload the map layer
    RMMapTiledLayerView *tiledLayerView = [_tiledLayersSuperview.subviews objectAtIndex:index];
//    tiledLayerView.layer.contents = nil;
    [tiledLayerView setNeedsDisplay];
}

#pragma mark - Properties

- (UIView *)backgroundView
{
    return _backgroundView;
}

- (void)setBackgroundView:(UIView *)aView
{
    if ([_backgroundView isEqual:aView])
        return;

    if (_backgroundView)
        [_backgroundView removeFromSuperview];

    if ( ! aView)
    {
        if ( ! _loadingTileView)
            _loadingTileView = [[RMLoadingTileView alloc] initWithFrame:self.bounds];

        aView = _loadingTileView;
    }
    else
        _loadingTileView = nil;

    _backgroundView = aView;

    _backgroundView.frame = self.bounds;

    [self insertSubview:_backgroundView atIndex:0];
}

- (void)setBackgroundImage:(UIImage *)backgroundImage
{
    if (backgroundImage)
    {
        [self setBackgroundView:[[UIView alloc] initWithFrame:self.bounds]];
        self.backgroundView.layer.contents = (id)backgroundImage.CGImage;
    }
    else
    {
        [self setBackgroundView:nil];
    }
}

- (double)metersPerPixel
{
    return _metersPerPixel;
}

- (void)setMetersPerPixel:(double)newMetersPerPixel
{
    [self setMetersPerPixel:newMetersPerPixel animated:YES];
}

- (void)setMetersPerPixel:(double)newMetersPerPixel animated:(BOOL)animated
{
    double factor = self.metersPerPixel / newMetersPerPixel;

    [self zoomByFactor:factor near:CGPointMake(self.bounds.size.width/2.0, self.bounds.size.height/2.0) animated:animated];
}

- (double)scaledMetersPerPixel
{
    return _metersPerPixel / _screenScale;
}

// From http://stackoverflow.com/questions/610193/calculating-pixel-size-on-an-iphone
#define kiPhone3MillimeteresPerPixel 0.1558282
#define kiPhone4MillimetersPerPixel (0.0779 * 2.0)

#define iPad1MillimetersPerPixel 0.1924
#define iPad3MillimetersPerPixel (0.09621 * 2.0)

- (double)scaleDenominator
{
    double iphoneMillimetersPerPixel;

    BOOL deviceIsIPhone = ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone);
    BOOL deviceHasRetinaDisplay = (_screenScale > 1.0);

    if (deviceHasRetinaDisplay)
        iphoneMillimetersPerPixel = (deviceIsIPhone ? kiPhone4MillimetersPerPixel : iPad3MillimetersPerPixel);
    else
        iphoneMillimetersPerPixel = (deviceIsIPhone ? kiPhone3MillimeteresPerPixel : iPad1MillimetersPerPixel);

    return ((_metersPerPixel * 1000.0) / iphoneMillimetersPerPixel);
}

- (void)setMinZoom:(float)newMinZoom
{
    float boundingDimension = fmaxf(self.bounds.size.width, self.bounds.size.height);
    float tileSideLength    = _tileSourcesContainer.tileSideLength;
    float clampedMinZoom    = log2(boundingDimension / tileSideLength);

    if (newMinZoom < clampedMinZoom)
        newMinZoom = clampedMinZoom;

    if (newMinZoom < 0.0)
        newMinZoom = 0.0;

    _minZoom = newMinZoom;

//    RMLog(@"New minZoom:%f", newMinZoom);

    _mapScrollView.minimumZoomScale = exp2f(newMinZoom);
}

- (float)tileSourcesMinZoom
{
    return self.tileSourcesContainer.minZoom;
}

- (void)setTileSourcesMinZoom:(float)tileSourcesMinZoom
{
    tileSourcesMinZoom = ceilf(tileSourcesMinZoom) - 0.99;

    if ( ! self.adjustTilesForRetinaDisplay && _screenScale > 1.0)
        tileSourcesMinZoom -= 1.0;

    [self setMinZoom:tileSourcesMinZoom];
}

- (void)setMaxZoom:(float)newMaxZoom
{
    if (newMaxZoom < 0.0)
        newMaxZoom = 0.0;

    _maxZoom = newMaxZoom;

//    RMLog(@"New maxZoom:%f", newMaxZoom);

    _mapScrollView.maximumZoomScale = exp2f(newMaxZoom);
}

- (float)tileSourcesMaxZoom
{
    return self.tileSourcesContainer.maxZoom;
}

- (void)setTileSourcesMaxZoom:(float)tileSourcesMaxZoom
{
    tileSourcesMaxZoom = floorf(tileSourcesMaxZoom);

    if ( ! self.adjustTilesForRetinaDisplay && _screenScale > 1.0)
        tileSourcesMaxZoom -= 1.0;

    [self setMaxZoom:tileSourcesMaxZoom];
}

- (float)zoom
{
    return _zoom;
}

// if #zoom is outside of range #minZoom to #maxZoom, zoom level is clamped to that range.
- (void)setZoom:(float)newZoom
{
    if (_zoom == newZoom)
        return;

    [self registerZoomEventByUser:NO];

    _zoom = (newZoom > _maxZoom) ? _maxZoom : newZoom;
    _zoom = (_zoom < _minZoom) ? _minZoom : _zoom;

//    RMLog(@"New zoom:%f", _zoom);

    _mapScrollView.zoomScale = exp2f(_zoom);

    [self completeZoomEventAfterDelay:0];
}

- (float)tileSourcesZoom
{
    float zoom = ceilf(_zoom);

    if ( ! self.adjustTilesForRetinaDisplay && _screenScale > 1.0)
        zoom += 1.0;

    return zoom;
}

- (void)setTileSourcesZoom:(float)tileSourcesZoom
{
    tileSourcesZoom = floorf(tileSourcesZoom);

    if ( ! self.adjustTilesForRetinaDisplay && _screenScale > 1.0)
        tileSourcesZoom -= 1.0;

    [self setZoom:tileSourcesZoom];
}

- (void)setClusteringEnabled:(BOOL)doEnableClustering
{
    _clusteringEnabled = doEnableClustering;

    [self correctPositionOfAllAnnotations];
}

- (void)setDecelerationMode:(RMMapDecelerationMode)aDecelerationMode
{
    _decelerationMode = aDecelerationMode;

    float decelerationRate = 0.0;

    if (aDecelerationMode == RMMapDecelerationNormal)
        decelerationRate = UIScrollViewDecelerationRateNormal;
    else if (aDecelerationMode == RMMapDecelerationFast)
        decelerationRate = UIScrollViewDecelerationRateFast;

    [_mapScrollView setDecelerationRate:decelerationRate];
}

- (BOOL)draggingEnabled
{
    return _draggingEnabled;
}

- (void)setDraggingEnabled:(BOOL)enableDragging
{
    _draggingEnabled = enableDragging;
    _mapScrollView.scrollEnabled = enableDragging;
}

- (BOOL)bouncingEnabled
{
    return _bouncingEnabled;
}

- (void)setBouncingEnabled:(BOOL)enableBouncing
{
    _bouncingEnabled = enableBouncing;
    _mapScrollView.bounces = enableBouncing;
    _mapScrollView.bouncesZoom = enableBouncing;
}

- (void)setAdjustTilesForRetinaDisplay:(BOOL)doAdjustTilesForRetinaDisplay
{
    if (_adjustTilesForRetinaDisplay == doAdjustTilesForRetinaDisplay)
        return;

    _adjustTilesForRetinaDisplay = doAdjustTilesForRetinaDisplay;

    RMProjectedPoint centerPoint = [self centerProjectedPoint];

    [self createMapView];

    [self setCenterProjectedPoint:centerPoint animated:NO];
}

- (float)adjustedZoomForRetinaDisplay
{
    if (!self.adjustTilesForRetinaDisplay && _screenScale > 1.0)
        return [self zoom] + 1.0;

    return [self zoom];
}

- (RMProjection *)projection
{
    return _projection;
}

- (RMFractalTileProjection *)mercatorToTileProjection
{
    return _mercatorToTileProjection;
}

- (void)setDebugTiles:(BOOL)shouldDebug;
{
    _debugTiles = shouldDebug;

    for (RMMapTiledLayerView *tiledLayerView in _tiledLayersSuperview.subviews)
    {
        tiledLayerView.layer.contents = nil;
        [tiledLayerView.layer setNeedsDisplay];
    }
}

- (void)setShowLogoBug:(BOOL)showLogoBug
{
    if (showLogoBug && ! _logoBug)
    {
        _logoBug = [[UIImageView alloc] initWithImage:[RMMapView resourceImageNamed:@"mapbox.png"]];
        _logoBug.frame = CGRectMake(8, self.bounds.size.height - _logoBug.bounds.size.height - 4, _logoBug.bounds.size.width, _logoBug.bounds.size.height);
        _logoBug.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleRightMargin;
        _logoBug.translatesAutoresizingMaskIntoConstraints = NO;
        [self addSubview:_logoBug];
    }
    else if ( ! showLogoBug && _logoBug)
    {
        [_logoBug removeFromSuperview];
    }

    _showLogoBug = showLogoBug;
}

- (void)tintColorDidChange
{
    if (CLLocationCoordinate2DIsValid(self.userLocation.coordinate))
    {
        // update user dot
        //
        [self.userLocation updateTintColor];

        // update user halo
        //
        UIImage *haloImage = [self trackingDotHaloImage];
        _userHaloTrackingView.image = haloImage;
        [(RMMarker *)_trackingHaloAnnotation.layer replaceUIImage:haloImage];

        // update accuracy circle
        //
        ((RMCircle *)_accuracyCircleAnnotation.layer).fillColor = [self.tintColor colorWithAlphaComponent:0.1];
    }

    if (_userTrackingBarButtonItem)
    {
        if (self.tintAdjustmentMode == UIViewTintAdjustmentModeDimmed || _userTrackingBarButtonItem.tintAdjustmentMode == UIViewTintAdjustmentModeDimmed)
        {
            _userTrackingBarButtonItem.tintAdjustmentMode = self.tintAdjustmentMode;
            _userTrackingBarButtonItem.tintColor = self.tintColor;
        }
    }

    for (RMAnnotation *annotation in self.annotations)
    {
        if ([annotation isKindOfClass:[RMPointAnnotation class]] && annotation.isAnnotationVisibleOnScreen)
        {
            [annotation.layer removeFromSuperlayer];
            annotation.layer = nil;
            [_overlayView addSublayer:annotation.layer];
        }
    }

    [self correctPositionOfAllAnnotations];

    if (_currentCallout)
        _currentCallout.tintColor = self.tintColor;
}

#pragma mark -
#pragma mark LatLng/Pixel translation functions

- (CGPoint)projectedPointToPixel:(RMProjectedPoint)projectedPoint
{
    RMProjectedRect planetBounds = _projection.planetBounds;
    RMProjectedPoint normalizedProjectedPoint;
	normalizedProjectedPoint.x = projectedPoint.x + fabs(planetBounds.origin.x);
	normalizedProjectedPoint.y = projectedPoint.y + fabs(planetBounds.origin.y);

    // \bug: There is a rounding error here for high zoom levels
    CGPoint projectedPixel = CGPointMake((normalizedProjectedPoint.x / _metersPerPixel) - _mapScrollView.contentOffset.x, (_mapScrollView.contentSize.height - (normalizedProjectedPoint.y / _metersPerPixel)) - _mapScrollView.contentOffset.y);

//    RMLog(@"pointToPixel: {%f,%f} -> {%f,%f}", projectedPoint.x, projectedPoint.y, projectedPixel.x, projectedPixel.y);

    return projectedPixel;
}

- (CGPoint)coordinateToPixel:(CLLocationCoordinate2D)coordinate
{
    return [self projectedPointToPixel:[_projection coordinateToProjectedPoint:coordinate]];
}

- (RMProjectedPoint)pixelToProjectedPoint:(CGPoint)pixelCoordinate
{
    RMProjectedRect planetBounds = _projection.planetBounds;
    RMProjectedPoint normalizedProjectedPoint;
    normalizedProjectedPoint.x = ((pixelCoordinate.x + _mapScrollView.contentOffset.x) * _metersPerPixel) - fabs(planetBounds.origin.x);
    normalizedProjectedPoint.y = ((_mapScrollView.contentSize.height - _mapScrollView.contentOffset.y - pixelCoordinate.y) * _metersPerPixel) - fabs(planetBounds.origin.y);

//    RMLog(@"pixelToPoint: {%f,%f} -> {%f,%f}", pixelCoordinate.x, pixelCoordinate.y, normalizedProjectedPoint.x, normalizedProjectedPoint.y);

    return normalizedProjectedPoint;
}

- (CLLocationCoordinate2D)pixelToCoordinate:(CGPoint)pixelCoordinate
{
    return [_projection projectedPointToCoordinate:[self pixelToProjectedPoint:pixelCoordinate]];
}

- (RMProjectedPoint)coordinateToProjectedPoint:(CLLocationCoordinate2D)coordinate
{
    return [_projection coordinateToProjectedPoint:coordinate];
}

- (CLLocationCoordinate2D)projectedPointToCoordinate:(RMProjectedPoint)projectedPoint
{
    return [_projection projectedPointToCoordinate:projectedPoint];
}

- (RMProjectedSize)viewSizeToProjectedSize:(CGSize)screenSize
{
    return RMProjectedSizeMake(screenSize.width * _metersPerPixel, screenSize.height * _metersPerPixel);
}

- (CGSize)projectedSizeToViewSize:(RMProjectedSize)projectedSize
{
    return CGSizeMake(projectedSize.width / _metersPerPixel, projectedSize.height / _metersPerPixel);
}

- (RMProjectedPoint)projectedOrigin
{
    CGPoint origin = CGPointMake(_mapScrollView.contentOffset.x, _mapScrollView.contentSize.height - _mapScrollView.contentOffset.y);

    RMProjectedRect planetBounds = _projection.planetBounds;
    RMProjectedPoint normalizedProjectedPoint;
    normalizedProjectedPoint.x = (origin.x * _metersPerPixel) - fabs(planetBounds.origin.x);
    normalizedProjectedPoint.y = (origin.y * _metersPerPixel) - fabs(planetBounds.origin.y);

//    RMLog(@"projectedOrigin: {%f,%f}", normalizedProjectedPoint.x, normalizedProjectedPoint.y);

    return normalizedProjectedPoint;
}

- (RMProjectedSize)projectedViewSize
{
    return RMProjectedSizeMake(self.bounds.size.width * _metersPerPixel, self.bounds.size.height * _metersPerPixel);
}

- (CLLocationCoordinate2D)normalizeCoordinate:(CLLocationCoordinate2D)coordinate
{
	if (coordinate.longitude > 180.0)
        coordinate.longitude -= 360.0;

	coordinate.longitude /= 360.0;
	coordinate.longitude += 0.5;
	coordinate.latitude = 0.5 - ((log(tan((M_PI_4) + ((0.5 * M_PI * coordinate.latitude) / 180.0))) / M_PI) / 2.0);

	return coordinate;
}

- (RMTile)tileWithCoordinate:(CLLocationCoordinate2D)coordinate andZoom:(int)tileZoom
{
	int scale = (1<<tileZoom);
	CLLocationCoordinate2D normalizedCoordinate = [self normalizeCoordinate:coordinate];

	RMTile returnTile;
	returnTile.x = (int)(normalizedCoordinate.longitude * scale);
	returnTile.y = (int)(normalizedCoordinate.latitude * scale);
	returnTile.zoom = tileZoom;

	return returnTile;
}

- (RMSphericalTrapezium)latitudeLongitudeBoundingBoxForTile:(RMTile)aTile
{
    RMProjectedRect planetBounds = _projection.planetBounds;

    double scale = (1<<aTile.zoom);
    double tileSideLength = [_tileSourcesContainer tileSideLength];
    double tileMetersPerPixel = planetBounds.size.width / (tileSideLength * scale);

    CGPoint bottomLeft = CGPointMake(aTile.x * tileSideLength, (scale - aTile.y - 1) * tileSideLength);

    RMProjectedRect normalizedProjectedRect;
    normalizedProjectedRect.origin.x = (bottomLeft.x * tileMetersPerPixel) - fabs(planetBounds.origin.x);
    normalizedProjectedRect.origin.y = (bottomLeft.y * tileMetersPerPixel) - fabs(planetBounds.origin.y);
    normalizedProjectedRect.size.width = tileSideLength * tileMetersPerPixel;
    normalizedProjectedRect.size.height = tileSideLength * tileMetersPerPixel;

    RMSphericalTrapezium boundingBox;
    boundingBox.southWest = [self projectedPointToCoordinate:
                             RMProjectedPointMake(normalizedProjectedRect.origin.x,
                                                  normalizedProjectedRect.origin.y)];
    boundingBox.northEast = [self projectedPointToCoordinate:
                             RMProjectedPointMake(normalizedProjectedRect.origin.x + normalizedProjectedRect.size.width,
                                                  normalizedProjectedRect.origin.y + normalizedProjectedRect.size.height)];

//    RMLog(@"Bounding box for tile (%d,%d) at zoom %d: {%f,%f} {%f,%f)", aTile.x, aTile.y, aTile.zoom, boundingBox.southWest.longitude, boundingBox.southWest.latitude, boundingBox.northEast.longitude, boundingBox.northEast.latitude);

    return boundingBox;
}

#pragma mark -
#pragma mark Bounds

- (RMSphericalTrapezium)latitudeLongitudeBoundingBox
{
    return [self latitudeLongitudeBoundingBoxFor:[self bounds]];
}

- (RMSphericalTrapezium)latitudeLongitudeBoundingBoxFor:(CGRect)rect
{
    RMSphericalTrapezium boundingBox;
    CGPoint northwestScreen = rect.origin;

    CGPoint southeastScreen;
    southeastScreen.x = rect.origin.x + rect.size.width;
    southeastScreen.y = rect.origin.y + rect.size.height;

    CGPoint northeastScreen, southwestScreen;
    northeastScreen.x = southeastScreen.x;
    northeastScreen.y = northwestScreen.y;
    southwestScreen.x = northwestScreen.x;
    southwestScreen.y = southeastScreen.y;

    CLLocationCoordinate2D northeastLL, northwestLL, southeastLL, southwestLL;
    northeastLL = [self pixelToCoordinate:northeastScreen];
    northwestLL = [self pixelToCoordinate:northwestScreen];
    southeastLL = [self pixelToCoordinate:southeastScreen];
    southwestLL = [self pixelToCoordinate:southwestScreen];

    boundingBox.northEast.latitude = fmax(northeastLL.latitude, northwestLL.latitude);
    boundingBox.southWest.latitude = fmin(southeastLL.latitude, southwestLL.latitude);

    // westerly computations:
    // -179, -178 -> -179 (min)
    // -179, 179  -> 179 (max)
    if (fabs(northwestLL.longitude - southwestLL.longitude) <= kMaxLong)
        boundingBox.southWest.longitude = fmin(northwestLL.longitude, southwestLL.longitude);
    else
        boundingBox.southWest.longitude = fmax(northwestLL.longitude, southwestLL.longitude);

    if (fabs(northeastLL.longitude - southeastLL.longitude) <= kMaxLong)
        boundingBox.northEast.longitude = fmax(northeastLL.longitude, southeastLL.longitude);
    else
        boundingBox.northEast.longitude = fmin(northeastLL.longitude, southeastLL.longitude);

    return boundingBox;
}

#pragma mark -
#pragma mark Annotations

- (void)correctScreenPosition:(RMAnnotation *)annotation animated:(BOOL)animated
{
    RMProjectedRect planetBounds = _projection.planetBounds;
	RMProjectedPoint normalizedProjectedPoint;
	normalizedProjectedPoint.x = annotation.projectedLocation.x + fabs(planetBounds.origin.x);
	normalizedProjectedPoint.y = annotation.projectedLocation.y + fabs(planetBounds.origin.y);

    CGPoint newPosition = CGPointMake((normalizedProjectedPoint.x / _metersPerPixel) - _mapScrollView.contentOffset.x,
                                      _mapScrollView.contentSize.height - (normalizedProjectedPoint.y / _metersPerPixel) - _mapScrollView.contentOffset.y);

//    RMLog(@"Change annotation at {%f,%f} in mapView {%f,%f}", annotation.position.x, annotation.position.y, mapScrollView.contentSize.width, mapScrollView.contentSize.height);

    [annotation setPosition:newPosition animated:animated];
}

- (void)correctPositionOfAllAnnotationsIncludingInvisibles:(BOOL)correctAllAnnotations animated:(BOOL)animated
{
    // Prevent blurry movements
    [CATransaction begin];

    // Synchronize marker movement with the map scroll view
    if (animated && !_mapScrollView.isZooming)
    {
        [CATransaction setAnimationTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
        [CATransaction setAnimationDuration:0.30];
    }
    else
    {
        [CATransaction setDisableActions:YES];
    }

    _accumulatedDelta.x = 0.0;
    _accumulatedDelta.y = 0.0;
    [_overlayView moveLayersBy:_accumulatedDelta];

    if (self.quadTree)
    {
        if (!correctAllAnnotations || _mapScrollViewIsZooming)
        {
            for (RMAnnotation *annotation in _visibleAnnotations)
                [self correctScreenPosition:annotation animated:animated];

//            RMLog(@"%d annotations corrected", [visibleAnnotations count]);

            [CATransaction commit];

            return;
        }

        double boundingBoxBuffer = (kZoomRectPixelBuffer * _metersPerPixel);

        RMProjectedRect boundingBox = self.projectedBounds;
        boundingBox.origin.x -= boundingBoxBuffer;
        boundingBox.origin.y -= boundingBoxBuffer;
        boundingBox.size.width += (2.0 * boundingBoxBuffer);
        boundingBox.size.height += (2.0 * boundingBoxBuffer);

        NSArray *annotationsToCorrect = [self.quadTree annotationsInProjectedRect:boundingBox
                                                         createClusterAnnotations:self.clusteringEnabled
                                                         withProjectedClusterSize:RMProjectedSizeMake(self.clusterAreaSize.width * _metersPerPixel, self.clusterAreaSize.height * _metersPerPixel)
                                                    andProjectedClusterMarkerSize:RMProjectedSizeMake(self.clusterMarkerSize.width * _metersPerPixel, self.clusterMarkerSize.height * _metersPerPixel)
                                                                findGravityCenter:self.positionClusterMarkersAtTheGravityCenter];
        NSMutableSet *previousVisibleAnnotations = [[NSMutableSet alloc] initWithSet:_visibleAnnotations];

        for (RMAnnotation *annotation in annotationsToCorrect)
        {
            if (annotation.layer == nil && _delegateHasLayerForAnnotation)
                annotation.layer = [_delegate mapView:self layerForAnnotation:annotation];

            if (annotation.layer == nil)
                continue;

            if ([annotation.layer isKindOfClass:[RMMarker class]] && ! annotation.isUserLocationAnnotation)
                annotation.layer.transform = _annotationTransform;

            // Use the zPosition property to order the layer hierarchy
            if ( ! [_visibleAnnotations containsObject:annotation])
            {
                [_overlayView addSublayer:annotation.layer];
                [_visibleAnnotations addObject:annotation];
            }

            [self correctScreenPosition:annotation animated:animated];

            [previousVisibleAnnotations removeObject:annotation];
        }

        for (RMAnnotation *annotation in previousVisibleAnnotations)
        {
            if ( ! annotation.isUserLocationAnnotation)
            {
                if (_delegateHasWillHideLayerForAnnotation)
                    [_delegate mapView:self willHideLayerForAnnotation:annotation];

                annotation.layer = nil;

                if (_delegateHasDidHideLayerForAnnotation)
                    [_delegate mapView:self didHideLayerForAnnotation:annotation];

                [_visibleAnnotations removeObject:annotation];
            }
        }

        previousVisibleAnnotations = nil;

//        RMLog(@"%d annotations on screen, %d total", [overlayView sublayersCount], [annotations count]);
    }
    else
    {
        CALayer *lastLayer = nil;

        @synchronized (_annotations)
        {
            if (correctAllAnnotations)
            {
                for (RMAnnotation *annotation in _annotations)
                {
                    [self correctScreenPosition:annotation animated:animated];

                    if ([annotation isAnnotationWithinBounds:[self bounds]])
                    {
                        if (annotation.layer == nil && _delegateHasLayerForAnnotation)
                            annotation.layer = [_delegate mapView:self layerForAnnotation:annotation];

                        if (annotation.layer == nil)
                            continue;

                        if ([annotation.layer isKindOfClass:[RMMarker class]] && ! annotation.isUserLocationAnnotation)
                            annotation.layer.transform = _annotationTransform;

                        if (![_visibleAnnotations containsObject:annotation])
                        {
                            if (!lastLayer)
                                [_overlayView insertSublayer:annotation.layer atIndex:0];
                            else
                                [_overlayView insertSublayer:annotation.layer above:lastLayer];

                            [_visibleAnnotations addObject:annotation];
                        }

                        lastLayer = annotation.layer;
                    }
                    else
                    {
                        if ( ! annotation.isUserLocationAnnotation)
                        {
                            if (_delegateHasWillHideLayerForAnnotation)
                                [_delegate mapView:self willHideLayerForAnnotation:annotation];

                            annotation.layer = nil;
                            [_visibleAnnotations removeObject:annotation];

                            if (_delegateHasDidHideLayerForAnnotation)
                                [_delegate mapView:self didHideLayerForAnnotation:annotation];
                        }
                    }
                }
//                RMLog(@"%d annotations on screen, %d total", [overlayView sublayersCount], [annotations count]);
            }
            else
            {
                for (RMAnnotation *annotation in _visibleAnnotations)
                    [self correctScreenPosition:annotation animated:animated];

//                RMLog(@"%d annotations corrected", [visibleAnnotations count]);
            }
        }
    }

    [self correctOrderingOfAllAnnotations];

    [CATransaction commit];
}

- (void)correctPositionOfAllAnnotations
{
    [self correctPositionOfAllAnnotationsIncludingInvisibles:YES animated:NO];
}

- (void)correctOrderingOfAllAnnotations
{
    if ( ! _orderMarkersByYPosition)
        return;

    // sort annotation layer z-indexes so that they overlap properly
    //
    NSMutableArray *sortedAnnotations = [NSMutableArray arrayWithArray:[_visibleAnnotations allObjects]];

    [sortedAnnotations filterUsingPredicate:[NSPredicate predicateWithFormat:@"isUserLocationAnnotation = NO"]];

    [sortedAnnotations sortUsingComparator:^(id obj1, id obj2)
    {
        RMAnnotation *annotation1 = (RMAnnotation *)obj1;
        RMAnnotation *annotation2 = (RMAnnotation *)obj2;

        // clusters above/below non-clusters (based on _orderClusterMarkersAboveOthers)
        //
        if (   annotation1.isClusterAnnotation && ! annotation2.isClusterAnnotation)
            return (_orderClusterMarkersAboveOthers ? NSOrderedDescending : NSOrderedAscending);

        if ( ! annotation1.isClusterAnnotation &&   annotation2.isClusterAnnotation)
            return (_orderClusterMarkersAboveOthers ? NSOrderedAscending : NSOrderedDescending);

        // markers above shapes
        //
        if (   [annotation1.layer isKindOfClass:[RMMarker class]] && ! [annotation2.layer isKindOfClass:[RMMarker class]])
            return NSOrderedDescending;

        if ( ! [annotation1.layer isKindOfClass:[RMMarker class]] &&   [annotation2.layer isKindOfClass:[RMMarker class]])
            return NSOrderedAscending;

        // the rest in increasing y-position
        //
        CGPoint obj1Point = [self convertPoint:annotation1.position fromView:_overlayView];
        CGPoint obj2Point = [self convertPoint:annotation2.position fromView:_overlayView];

        if (obj1Point.y > obj2Point.y)
            return NSOrderedDescending;

        if (obj1Point.y < obj2Point.y)
            return NSOrderedAscending;

        return NSOrderedSame;
    }];

    for (CGFloat i = 0; i < [sortedAnnotations count]; i++)
        ((RMAnnotation *)[sortedAnnotations objectAtIndex:i]).layer.zPosition = (CGFloat)i;

    // bring any active callout annotation to the front
    //
    if (_currentAnnotation)
        _currentAnnotation.layer.zPosition = _currentCallout.layer.zPosition = MAXFLOAT;
}

- (NSArray *)annotations
{
    return [_annotations allObjects];
}

- (NSArray *)visibleAnnotations
{
    return [_visibleAnnotations allObjects];
}

- (void)addAnnotation:(RMAnnotation *)annotation
{
    @synchronized (_annotations)
    {
        if ([_annotations containsObject:annotation])
            return;

        [_annotations addObject:annotation];
        [self.quadTree addAnnotation:annotation];
    }

    if (_clusteringEnabled)
    {
        [self correctPositionOfAllAnnotations];
    }
    else
    {
        [self correctScreenPosition:annotation animated:NO];

        if (annotation.layer == nil && [annotation isAnnotationOnScreen] && _delegateHasLayerForAnnotation)
            annotation.layer = [_delegate mapView:self layerForAnnotation:annotation];

        if (annotation.layer)
        {
            [_overlayView addSublayer:annotation.layer];
            [_visibleAnnotations addObject:annotation];
        }

        [self correctOrderingOfAllAnnotations];
    }
}

- (void)addAnnotations:(NSArray *)newAnnotations
{
    @synchronized (_annotations)
    {
        [_annotations addObjectsFromArray:newAnnotations];
        [self.quadTree addAnnotations:newAnnotations];
    }

    [self correctPositionOfAllAnnotationsIncludingInvisibles:YES animated:NO];
}

- (void)removeAnnotation:(RMAnnotation *)annotation
{
    @synchronized (_annotations)
    {
        [_annotations removeObject:annotation];
        [_visibleAnnotations removeObject:annotation];
        [self.quadTree removeAnnotation:annotation];
        annotation.layer = nil;
    }

    [self correctPositionOfAllAnnotations];
}

- (void)removeAnnotations:(NSArray *)annotationsToRemove
{
    @synchronized (_annotations)
    {
        for (RMAnnotation *annotation in annotationsToRemove)
        {
            if ( ! annotation.isUserLocationAnnotation)
            {
                [_annotations removeObject:annotation];
                [_visibleAnnotations removeObject:annotation];
                [self.quadTree removeAnnotation:annotation];
                annotation.layer = nil;
            }
       }
    }

    [self correctPositionOfAllAnnotations];
}

- (void)removeAllAnnotations
{
    [self removeAnnotations:[_annotations allObjects]];
}

- (CGPoint)mapPositionForAnnotation:(RMAnnotation *)annotation
{
    [self correctScreenPosition:annotation animated:NO];
    return annotation.position;
}

#pragma mark -
#pragma mark User Location

- (void)setShowsUserLocation:(BOOL)newShowsUserLocation
{
    if (newShowsUserLocation == _showsUserLocation)
        return;

    _showsUserLocation = newShowsUserLocation;

    if (newShowsUserLocation)
    {
        if (_delegateHasWillStartLocatingUser)
            [_delegate mapViewWillStartLocatingUser:self];

        self.userLocation = [RMUserLocation annotationWithMapView:self coordinate:CLLocationCoordinate2DMake(MAXFLOAT, MAXFLOAT) andTitle:nil];

        _locationManager = [CLLocationManager new];
        _locationManager.headingFilter = 5.0;
        _locationManager.delegate = self;
        [_locationManager startUpdatingLocation];
    }
    else
    {
        [_locationManager stopUpdatingLocation];
        [_locationManager stopUpdatingHeading];
        _locationManager.delegate = nil;
         _locationManager = nil;

        if (_delegateHasDidStopLocatingUser)
            [_delegate mapViewDidStopLocatingUser:self];

        [self setUserTrackingMode:RMUserTrackingModeNone animated:YES];

        for (RMAnnotation *annotation in [NSArray arrayWithObjects:_trackingHaloAnnotation, _accuracyCircleAnnotation, self.userLocation, nil])
            [self removeAnnotation:annotation];

         _trackingHaloAnnotation = nil;
         _accuracyCircleAnnotation = nil;

        self.userLocation = nil;
    }
}

- (void)setUserLocation:(RMUserLocation *)newUserLocation
{
    if ( ! [newUserLocation isEqual:_userLocation])
        _userLocation = newUserLocation;
}

- (BOOL)isUserLocationVisible
{
    if (self.userLocation)
    {
        CGPoint locationPoint = [self mapPositionForAnnotation:self.userLocation];

        CGRect locationRect = CGRectMake(locationPoint.x - self.userLocation.location.horizontalAccuracy,
                                         locationPoint.y - self.userLocation.location.horizontalAccuracy,
                                         self.userLocation.location.horizontalAccuracy * 2,
                                         self.userLocation.location.horizontalAccuracy * 2);

        return CGRectIntersectsRect([self bounds], locationRect);
    }

    return NO;
}

- (void)setUserTrackingMode:(RMUserTrackingMode)mode
{
    [self setUserTrackingMode:mode animated:YES];
}

- (void)setUserTrackingMode:(RMUserTrackingMode)mode animated:(BOOL)animated
{
    if (mode == _userTrackingMode)
        return;

    if (mode == RMUserTrackingModeFollowWithHeading && ! CLLocationCoordinate2DIsValid(self.userLocation.coordinate))
        mode = RMUserTrackingModeNone;

    _userTrackingMode = mode;

    switch (_userTrackingMode)
    {
        case RMUserTrackingModeNone:
        default:
        {
            [_locationManager stopUpdatingHeading];

            [CATransaction setAnimationDuration:0.5];
            [CATransaction setAnimationTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];

            [UIView animateWithDuration:(animated ? 0.5 : 0.0)
                                  delay:0.0
                                options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationCurveEaseInOut
                             animations:^(void)
                             {
                                 _mapTransform = CGAffineTransformIdentity;
                                 _annotationTransform = CATransform3DIdentity;

                                 _mapScrollView.transform = _mapTransform;
                                 _compassButton.transform = _mapTransform;
                                 _overlayView.transform   = _mapTransform;

                                 _compassButton.alpha = 0;

                                 for (RMAnnotation *annotation in _annotations)
                                     if ([annotation.layer isKindOfClass:[RMMarker class]] && ! annotation.isUserLocationAnnotation)
                                         annotation.layer.transform = _annotationTransform;
                             }
                             completion:nil];

            [CATransaction commit];

            if (_userLocationTrackingView || _userHeadingTrackingView || _userHaloTrackingView)
            {
                [_userLocationTrackingView removeFromSuperview]; _userLocationTrackingView = nil;
                [_userHeadingTrackingView removeFromSuperview]; _userHeadingTrackingView = nil;
                [_userHaloTrackingView removeFromSuperview]; _userHaloTrackingView = nil;
            }

            self.userLocation.layer.hidden = NO;

            break;
        }
        case RMUserTrackingModeFollow:
        {
            self.showsUserLocation = YES;

            [_locationManager stopUpdatingHeading];

            if (self.userLocation)
                #pragma clang diagnostic push
                #pragma clang diagnostic ignored "-Wdeprecated-declarations"
                [self locationManager:_locationManager didUpdateToLocation:self.userLocation.location fromLocation:self.userLocation.location];
                #pragma clang diagnostic pop

            if (_userLocationTrackingView || _userHeadingTrackingView || _userHaloTrackingView)
            {
                [_userLocationTrackingView removeFromSuperview]; _userLocationTrackingView = nil;
                [_userHeadingTrackingView removeFromSuperview]; _userHeadingTrackingView = nil;
                [_userHaloTrackingView removeFromSuperview]; _userHaloTrackingView = nil;
            }

            [CATransaction setAnimationDuration:0.5];
            [CATransaction setAnimationTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];

            [UIView animateWithDuration:(animated ? 0.5 : 0.0)
                                  delay:0.0
                                options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationCurveEaseInOut
                             animations:^(void)
                             {
                                 _mapTransform = CGAffineTransformIdentity;
                                 _annotationTransform = CATransform3DIdentity;

                                 _mapScrollView.transform = _mapTransform;
                                 _compassButton.transform = _mapTransform;
                                 _overlayView.transform   = _mapTransform;

                                 _compassButton.alpha = 0;

                                 for (RMAnnotation *annotation in _annotations)
                                     if ([annotation.layer isKindOfClass:[RMMarker class]] && ! annotation.isUserLocationAnnotation)
                                         annotation.layer.transform = _annotationTransform;
                             }
                             completion:nil];

            [CATransaction commit];

            self.userLocation.layer.hidden = NO;

            break;
        }
        case RMUserTrackingModeFollowWithHeading:
        {
            self.showsUserLocation = YES;

            self.userLocation.layer.hidden = YES;

            _userHaloTrackingView = [[UIImageView alloc] initWithImage:[self trackingDotHaloImage]];

            _userHaloTrackingView.center = CGPointMake(round([self bounds].size.width  / 2),
                                                       round([self bounds].size.height / 2));

            _userHaloTrackingView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin  |
                                                     UIViewAutoresizingFlexibleRightMargin |
                                                     UIViewAutoresizingFlexibleTopMargin   |
                                                     UIViewAutoresizingFlexibleBottomMargin;

            [self insertSubview:_userHaloTrackingView belowSubview:_overlayView];

            _userHeadingTrackingView = [[UIImageView alloc] initWithImage:[RMMapView resourceImageNamed:@"HeadingAngleLarge.png"]];

            _userHeadingTrackingView.frame = CGRectMake((self.bounds.size.width  / 2) - (_userHeadingTrackingView.bounds.size.width / 2),
                                                        (self.bounds.size.height / 2) - _userHeadingTrackingView.bounds.size.height,
                                                        _userHeadingTrackingView.bounds.size.width,
                                                        _userHeadingTrackingView.bounds.size.height * 2);

            _userHeadingTrackingView.contentMode = UIViewContentModeTop;

            _userHeadingTrackingView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin  |
                                                        UIViewAutoresizingFlexibleRightMargin |
                                                        UIViewAutoresizingFlexibleTopMargin   |
                                                        UIViewAutoresizingFlexibleBottomMargin;

            _userHeadingTrackingView.alpha = 0.0;

            [self insertSubview:_userHeadingTrackingView belowSubview:_overlayView];

            _userLocationTrackingView = [[UIImageView alloc] initWithImage:[UIImage imageWithCGImage:(CGImageRef)self.userLocation.layer.contents
                                                                                               scale:self.userLocation.layer.contentsScale
                                                                                         orientation:UIImageOrientationUp]];

            _userLocationTrackingView.center = CGPointMake(round([self bounds].size.width  / 2), 
                                                           round([self bounds].size.height / 2));

            _userLocationTrackingView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin  |
                                                         UIViewAutoresizingFlexibleRightMargin |
                                                         UIViewAutoresizingFlexibleTopMargin   |
                                                         UIViewAutoresizingFlexibleBottomMargin;
            
            [self insertSubview:_userLocationTrackingView aboveSubview:_userHeadingTrackingView];

            if (self.zoom < 3)
                [self zoomByFactor:exp2f(3 - [self zoom]) near:self.center animated:YES];

            if (self.userLocation)
                #pragma clang diagnostic push
                #pragma clang diagnostic ignored "-Wdeprecated-declarations"
                [self locationManager:_locationManager didUpdateToLocation:self.userLocation.location fromLocation:self.userLocation.location];
                #pragma clang diagnostic pop

            [self updateHeadingForDeviceOrientation];

            [_locationManager startUpdatingHeading];

            break;
        }
    }

    if (_delegateHasDidChangeUserTrackingMode)
        [_delegate mapView:self didChangeUserTrackingMode:_userTrackingMode animated:animated];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    if ( ! _showsUserLocation || _mapScrollView.isDragging || ! newLocation || ! CLLocationCoordinate2DIsValid(newLocation.coordinate))
        return;

    if ([newLocation distanceFromLocation:oldLocation])
    {
        self.userLocation.location = newLocation;

        if (_delegateHasDidUpdateUserLocation)
            [_delegate mapView:self didUpdateUserLocation:self.userLocation];
    }

    if (self.userTrackingMode != RMUserTrackingModeNone)
    {
        // center on user location unless we're already centered there (or very close)
        //
        CGPoint mapCenterPoint    = [self convertPoint:self.center fromView:self.superview];
        CGPoint userLocationPoint = [self mapPositionForAnnotation:self.userLocation];

        if (fabsf(userLocationPoint.x - mapCenterPoint.x) > 1.0 || fabsf(userLocationPoint.y - mapCenterPoint.y) > 1.0)
        {
            if (round(_zoom) >= 10)
            {
                // at sufficient detail, just re-center the map; don't zoom
                //
                [self setCenterCoordinate:self.userLocation.location.coordinate animated:YES];
            }
            else
            {
                // otherwise re-center and zoom in to near accuracy confidence
                //
                float delta = (newLocation.horizontalAccuracy / 110000) * 1.2; // approx. meter per degree latitude, plus some margin

                CLLocationCoordinate2D desiredSouthWest = CLLocationCoordinate2DMake(newLocation.coordinate.latitude  - delta,
                                                                                     newLocation.coordinate.longitude - delta);

                CLLocationCoordinate2D desiredNorthEast = CLLocationCoordinate2DMake(newLocation.coordinate.latitude  + delta,
                                                                                     newLocation.coordinate.longitude + delta);

                CGFloat pixelRadius = fminf(self.bounds.size.width, self.bounds.size.height) / 2;

                CLLocationCoordinate2D actualSouthWest = [self pixelToCoordinate:CGPointMake(userLocationPoint.x - pixelRadius, userLocationPoint.y - pixelRadius)];
                CLLocationCoordinate2D actualNorthEast = [self pixelToCoordinate:CGPointMake(userLocationPoint.x + pixelRadius, userLocationPoint.y + pixelRadius)];

                if (desiredNorthEast.latitude  != actualNorthEast.latitude  ||
                    desiredNorthEast.longitude != actualNorthEast.longitude ||
                    desiredSouthWest.latitude  != actualSouthWest.latitude  ||
                    desiredSouthWest.longitude != actualSouthWest.longitude)
                {
                    [self zoomWithLatitudeLongitudeBoundsSouthWest:desiredSouthWest northEast:desiredNorthEast animated:YES];
                }
            }
        }
    }

    if ( ! _accuracyCircleAnnotation)
    {
        _accuracyCircleAnnotation = [RMAnnotation annotationWithMapView:self coordinate:newLocation.coordinate andTitle:nil];
        _accuracyCircleAnnotation.annotationType = kRMAccuracyCircleAnnotationTypeName;
        _accuracyCircleAnnotation.clusteringEnabled = NO;
        _accuracyCircleAnnotation.enabled = NO;
        _accuracyCircleAnnotation.layer = [[RMCircle alloc] initWithView:self radiusInMeters:newLocation.horizontalAccuracy];
        _accuracyCircleAnnotation.layer.zPosition = -MAXFLOAT;
        _accuracyCircleAnnotation.isUserLocationAnnotation = YES;

        ((RMCircle *)_accuracyCircleAnnotation.layer).lineColor = (RMPreVersion7 ? [UIColor colorWithRed:0.378 green:0.552 blue:0.827 alpha:0.7] : [UIColor clearColor]);
        ((RMCircle *)_accuracyCircleAnnotation.layer).fillColor = (RMPreVersion7 ? [UIColor colorWithRed:0.378 green:0.552 blue:0.827 alpha:0.15] : [self.tintColor colorWithAlphaComponent:0.1]);

        ((RMCircle *)_accuracyCircleAnnotation.layer).lineWidthInPixels = 2.0;

        [self addAnnotation:_accuracyCircleAnnotation];
    }

    if ( ! oldLocation)
    {
        // make accuracy circle bounce until we get our second update
        //
        [CATransaction begin];
        [CATransaction setAnimationDuration:0.75];
        [CATransaction setAnimationTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];

        CABasicAnimation *bounceAnimation = [CABasicAnimation animationWithKeyPath:@"transform"];
        bounceAnimation.repeatCount = MAXFLOAT;
        bounceAnimation.fromValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(1.2, 1.2, 1.0)];
        bounceAnimation.toValue   = [NSValue valueWithCATransform3D:CATransform3DMakeScale(0.8, 0.8, 1.0)];
        bounceAnimation.removedOnCompletion = NO;
        bounceAnimation.autoreverses = YES;

        [_accuracyCircleAnnotation.layer addAnimation:bounceAnimation forKey:@"animateScale"];

        [CATransaction commit];
    }
    else
    {
        [_accuracyCircleAnnotation.layer removeAnimationForKey:@"animateScale"];
    }

    if ([newLocation distanceFromLocation:oldLocation])
        _accuracyCircleAnnotation.coordinate = newLocation.coordinate;

    if (newLocation.horizontalAccuracy != oldLocation.horizontalAccuracy)
        ((RMCircle *)_accuracyCircleAnnotation.layer).radiusInMeters = newLocation.horizontalAccuracy;

    if ( ! _trackingHaloAnnotation)
    {
        _trackingHaloAnnotation = [RMAnnotation annotationWithMapView:self coordinate:newLocation.coordinate andTitle:nil];
        _trackingHaloAnnotation.annotationType = kRMTrackingHaloAnnotationTypeName;
        _trackingHaloAnnotation.clusteringEnabled = NO;
        _trackingHaloAnnotation.enabled = NO;

        // create image marker
        //
        _trackingHaloAnnotation.layer = [[RMMarker alloc] initWithUIImage:[self trackingDotHaloImage]];
        _trackingHaloAnnotation.layer.zPosition = -MAXFLOAT + 1;
        _trackingHaloAnnotation.isUserLocationAnnotation = YES;

        [CATransaction begin];

        if (RMPreVersion7)
        {
            [CATransaction setAnimationDuration:2.5];
            [CATransaction setAnimationTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
        }
        else
        {
            [CATransaction setAnimationDuration:3.5];
            [CATransaction setAnimationTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut]];
        }

        // scale out radially
        //
        CABasicAnimation *boundsAnimation = [CABasicAnimation animationWithKeyPath:@"transform"];
        boundsAnimation.repeatCount = MAXFLOAT;
        boundsAnimation.fromValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1.0)];
        boundsAnimation.toValue   = [NSValue valueWithCATransform3D:CATransform3DMakeScale(2.0, 2.0, 1.0)];
        boundsAnimation.removedOnCompletion = NO;

        [_trackingHaloAnnotation.layer addAnimation:boundsAnimation forKey:@"animateScale"];

        // go transparent as scaled out
        //
        CABasicAnimation *opacityAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
        opacityAnimation.repeatCount = MAXFLOAT;
        opacityAnimation.fromValue = [NSNumber numberWithFloat:1.0];
        opacityAnimation.toValue   = [NSNumber numberWithFloat:-1.0];
        opacityAnimation.removedOnCompletion = NO;

        [_trackingHaloAnnotation.layer addAnimation:opacityAnimation forKey:@"animateOpacity"];

        [CATransaction commit];

        [self addAnnotation:_trackingHaloAnnotation];
    }

    if ([newLocation distanceFromLocation:oldLocation])
        _trackingHaloAnnotation.coordinate = newLocation.coordinate;

    self.userLocation.layer.hidden = ( ! CLLocationCoordinate2DIsValid(self.userLocation.coordinate) || self.userTrackingMode == RMUserTrackingModeFollowWithHeading);

    if (_userLocationTrackingView)
        _userLocationTrackingView.hidden = ! CLLocationCoordinate2DIsValid(self.userLocation.coordinate);

    _accuracyCircleAnnotation.layer.hidden = newLocation.horizontalAccuracy <= 10 || self.userLocation.hasCustomLayer;

    _trackingHaloAnnotation.layer.hidden = ( ! CLLocationCoordinate2DIsValid(self.userLocation.coordinate) || newLocation.horizontalAccuracy > 10 || self.userTrackingMode == RMUserTrackingModeFollowWithHeading || self.userLocation.hasCustomLayer);

    if (_userHaloTrackingView)
    {
        _userHaloTrackingView.hidden = ( ! CLLocationCoordinate2DIsValid(self.userLocation.coordinate) || newLocation.horizontalAccuracy > 10 || self.userLocation.hasCustomLayer);

        // ensure animations are copied from layer
        //
        if ( ! [_userHaloTrackingView.layer.animationKeys count])
            for (NSString *animationKey in _trackingHaloAnnotation.layer.animationKeys)
                [_userHaloTrackingView.layer addAnimation:[[_trackingHaloAnnotation.layer animationForKey:animationKey] copy] forKey:animationKey];
    }

    if ( ! [_annotations containsObject:self.userLocation])
        [self addAnnotation:self.userLocation];
}

- (BOOL)locationManagerShouldDisplayHeadingCalibration:(CLLocationManager *)manager
{
    if (self.displayHeadingCalibration)
        [_locationManager performSelector:@selector(dismissHeadingCalibrationDisplay) withObject:nil afterDelay:10.0];

    return self.displayHeadingCalibration;
}

- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading
{
    if ( ! _showsUserLocation || _mapScrollView.isDragging || newHeading.headingAccuracy < 0)
        return;

    if (newHeading.headingAccuracy > 40)
        _userHeadingTrackingView.image = [RMMapView resourceImageNamed:@"HeadingAngleLarge.png"];
    else if (newHeading.headingAccuracy >= 25 && newHeading.headingAccuracy <= 40)
        _userHeadingTrackingView.image = [RMMapView resourceImageNamed:@"HeadingAngleMedium.png"];
    else
        _userHeadingTrackingView.image = [RMMapView resourceImageNamed:@"HeadingAngleSmall.png"];

    self.userLocation.heading = newHeading;

    if (_delegateHasDidUpdateUserLocation)
        [_delegate mapView:self didUpdateUserLocation:self.userLocation];

    if (newHeading.trueHeading != 0 && self.userTrackingMode == RMUserTrackingModeFollowWithHeading)
    {
        if (_userHeadingTrackingView.alpha < 1.0)
            [UIView animateWithDuration:0.5 animations:^(void) { _userHeadingTrackingView.alpha = 1.0; }];

        [CATransaction begin];
        [CATransaction setAnimationDuration:0.5];
        [CATransaction setAnimationTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];

        [UIView animateWithDuration:0.5
                              delay:0.0
                            options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationCurveEaseInOut
                         animations:^(void)
                         {
                             CGFloat angle = (M_PI / -180) * newHeading.trueHeading;

                             _mapTransform = CGAffineTransformMakeRotation(angle);
                             _annotationTransform = CATransform3DMakeAffineTransform(CGAffineTransformMakeRotation(-angle));

                             _mapScrollView.transform = _mapTransform;
                             _compassButton.transform = _mapTransform;
                             _overlayView.transform   = _mapTransform;

                             _compassButton.alpha = 1.0;

                             for (RMAnnotation *annotation in _annotations)
                                 if ([annotation.layer isKindOfClass:[RMMarker class]] && ! annotation.isUserLocationAnnotation)
                                     annotation.layer.transform = _annotationTransform;

                             [self correctPositionOfAllAnnotations];
                         }
                         completion:nil];

        [CATransaction commit];
    }
}

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    if (status == kCLAuthorizationStatusDenied || status == kCLAuthorizationStatusRestricted)
    {
        self.userTrackingMode  = RMUserTrackingModeNone;
        self.showsUserLocation = NO;
    }
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    if ([error code] == kCLErrorDenied)
    {
        self.userTrackingMode  = RMUserTrackingModeNone;
        self.showsUserLocation = NO;

        if (_delegateHasDidFailToLocateUserWithError)
            [_delegate mapView:self didFailToLocateUserWithError:error];
    }
}

- (void)updateHeadingForDeviceOrientation
{
    if (_locationManager)
    {
        // note that right/left device and interface orientations are opposites (see UIApplication.h)
        //
        switch ([[UIApplication sharedApplication] statusBarOrientation])
        {
            case (UIInterfaceOrientationLandscapeLeft):
            {
                _locationManager.headingOrientation = CLDeviceOrientationLandscapeRight;
                break;
            }
            case (UIInterfaceOrientationLandscapeRight):
            {
                _locationManager.headingOrientation = CLDeviceOrientationLandscapeLeft;
                break;
            }
            case (UIInterfaceOrientationPortraitUpsideDown):
            {
                _locationManager.headingOrientation = CLDeviceOrientationPortraitUpsideDown;
                break;
            }
            case (UIInterfaceOrientationPortrait):
            default:
            {
                _locationManager.headingOrientation = CLDeviceOrientationPortrait;
                break;
            }
        }
    }
}

- (void)tappedHeadingCompass:(id)sender
{
    self.userTrackingMode = RMUserTrackingModeFollow;
}

- (UIImage *)trackingDotHaloImage
{
    if (RMPreVersion7)
    {
        return [RMMapView resourceImageNamed:@"TrackingDotHalo.png"];
    }
    else
    {
        UIGraphicsBeginImageContextWithOptions(CGSizeMake(100, 100), NO, [[UIScreen mainScreen] scale]);
        CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(), [[self.tintColor colorWithAlphaComponent:0.75] CGColor]);
        CGContextFillEllipseInRect(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, 100, 100));
        UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        return finalImage;
    }
}

- (void)setUserTrackingBarButtonItem:(RMUserTrackingBarButtonItem *)userTrackingBarButtonItem
{
    _userTrackingBarButtonItem = userTrackingBarButtonItem;
}

#pragma mark -
#pragma mark Attribution

- (void)setHideAttribution:(BOOL)flag
{
    if (_hideAttribution == flag)
        return;

    _hideAttribution = flag;

    [self layoutSubviews];
}

- (UIViewController *)viewControllerPresentingAttribution
{
    return _viewControllerPresentingAttribution;
}

- (void)setViewControllerPresentingAttribution:(UIViewController *)viewController
{
    _viewControllerPresentingAttribution = viewController;
    
    if (_viewControllerPresentingAttribution && ! _attributionButton)
    {
        _attributionButton = [UIButton buttonWithType:UIButtonTypeInfoLight];
        _attributionButton.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin;
        _attributionButton.translatesAutoresizingMaskIntoConstraints = NO;
        [_attributionButton addTarget:self action:@selector(showAttribution:) forControlEvents:UIControlEventTouchUpInside];
        _attributionButton.frame = CGRectMake(self.bounds.size.width  - 30,
                                              self.bounds.size.height - 30,
                                              _attributionButton.bounds.size.width,
                                              _attributionButton.bounds.size.height);
        [self addSubview:_attributionButton];
    }
    else if ( ! _viewControllerPresentingAttribution && _attributionButton)
    {
        [_attributionButton removeFromSuperview];
    }
}

- (void)showAttribution:(id)sender
{
    if (_viewControllerPresentingAttribution)
    {
        RMAttributionViewController *attributionViewController = [[RMAttributionViewController alloc] initWithMapView:self];

        if (RMPostVersion7)
        {
            attributionViewController.view.tintColor = self.tintColor;
            attributionViewController.edgesForExtendedLayout = UIRectEdgeNone;

            if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad)
            {
                // show popover
                //
                _attributionPopover = [[UIPopoverController alloc] initWithContentViewController:attributionViewController];
                _attributionPopover.backgroundColor = [UIColor whiteColor];
                _attributionPopover.popoverContentSize = CGSizeMake(320, 320);
                _attributionPopover.delegate = self;
                [_attributionPopover presentPopoverFromRect:_attributionButton.frame
                                                     inView:self
                                   permittedArrowDirections:UIPopoverArrowDirectionDown
                                                   animated:NO];
            }
            else
            {
                // slide up see-through modal
                //
                attributionViewController.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone
                                                                                                                            target:self
                                                                                                                            action:@selector(dismissAttribution:)];

                UINavigationController *wrapper = [[UINavigationController alloc] initWithRootViewController:attributionViewController];
                wrapper.navigationBar.tintColor = self.tintColor;
                wrapper.modalPresentationStyle = UIModalPresentationCustom;
                wrapper.transitioningDelegate = self;
                [_viewControllerPresentingAttribution presentViewController:wrapper animated:YES completion:nil];
            }
        }
        else
        {
            // page curl reveal behind map
            //
            attributionViewController.modalTransitionStyle = UIModalTransitionStylePartialCurl;
            [_viewControllerPresentingAttribution presentViewController:attributionViewController animated:YES completion:nil];
        }
    }
}

- (void)dismissAttribution:(id)sender
{
    _viewControllerPresentingAttribution.modalViewController.modalPresentationStyle = UIModalTransitionStyleCoverVertical;
    [_viewControllerPresentingAttribution dismissModalViewControllerAnimated:YES];
}

- (void)popoverController:(UIPopoverController *)popoverController willRepositionPopoverToRect:(inout CGRect *)rect inView:(inout UIView **)view
{
    *rect = _attributionButton.frame;
}

- (void)popoverControllerDidDismissPopover:(UIPopoverController *)popoverController
{
    _attributionPopover = nil;
}

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source
{
    return self;
}

- (NSTimeInterval)transitionDuration:(id <UIViewControllerContextTransitioning>)transitionContext
{
    return (1.0 / 3.0);
}

- (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext
{
    UIView *inView   = [transitionContext containerView];
    UIView *fromView = [[transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey] view];
    UIView *toView   = [[transitionContext viewControllerForKey:UITransitionContextToViewControllerKey] view];

    [inView addSubview:toView];

    toView.center = CGPointMake(fromView.center.x, fromView.center.y + toView.bounds.size.height);

    [UIView animateWithDuration:[self transitionDuration:transitionContext]
                          delay:0
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^(void)
                     {
                         toView.center = fromView.center;
                     }
                     completion:^(BOOL finished)
                     {
                         [transitionContext completeTransition:YES];
                     }];

    // TODO: fix landscape orientation - https://devforums.apple.com/message/873505
}

@end