@mapgis/mapbox-gl 16.0.1 → 16.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (434) hide show
  1. package/dist/mapbox-gl.js +3 -3
  2. package/dist/mapbox-gl.js.map +1 -1
  3. package/package.json +1 -1
  4. package/.flowconfig +0 -61
  5. package/LICENSE.txt +0 -84
  6. package/README.md +0 -34
  7. package/build/banner.js +0 -4
  8. package/build/check-bundle-size.js +0 -140
  9. package/build/generate-access-token-script.js +0 -11
  10. package/build/generate-flow-typed-style-spec.js +0 -188
  11. package/build/generate-release-list.js +0 -21
  12. package/build/generate-struct-arrays.js +0 -237
  13. package/build/generate-style-code.js +0 -159
  14. package/build/mapbox-gl.js.flow +0 -3
  15. package/build/print-release-url.js +0 -6
  16. package/build/rollup_plugin_minify_style_spec.js +0 -20
  17. package/build/rollup_plugins.js +0 -80
  18. package/build/run-node +0 -3
  19. package/build/run-tap +0 -8
  20. package/build/test/build-tape.js +0 -19
  21. package/flow-typed/gl.js +0 -5
  22. package/flow-typed/jsdom.js +0 -18
  23. package/flow-typed/mapbox-gl-supported.js +0 -9
  24. package/flow-typed/mapbox-unitbezier.js +0 -14
  25. package/flow-typed/offscreen-canvas.js +0 -9
  26. package/flow-typed/pbf.js +0 -25
  27. package/flow-typed/point-geometry.js +0 -44
  28. package/flow-typed/potpack.js +0 -12
  29. package/flow-typed/sinon.js +0 -28
  30. package/flow-typed/vector-tile.js +0 -41
  31. package/src/css/mapbox-gl.css +0 -798
  32. package/src/css/svg/mapboxgl-ctrl-attrib.svg +0 -3
  33. package/src/css/svg/mapboxgl-ctrl-compass.svg +0 -4
  34. package/src/css/svg/mapboxgl-ctrl-fullscreen.svg +0 -3
  35. package/src/css/svg/mapboxgl-ctrl-geolocate.svg +0 -5
  36. package/src/css/svg/mapboxgl-ctrl-logo.svg +0 -20
  37. package/src/css/svg/mapboxgl-ctrl-shrink.svg +0 -3
  38. package/src/css/svg/mapboxgl-ctrl-zoom-in.svg +0 -3
  39. package/src/css/svg/mapboxgl-ctrl-zoom-out.svg +0 -3
  40. package/src/data/array_types.js +0 -1095
  41. package/src/data/bucket/circle_attributes.js +0 -9
  42. package/src/data/bucket/circle_bucket.js +0 -204
  43. package/src/data/bucket/fill_attributes.js +0 -9
  44. package/src/data/bucket/fill_bucket.js +0 -233
  45. package/src/data/bucket/fill_extrusion_attributes.js +0 -10
  46. package/src/data/bucket/fill_extrusion_bucket.js +0 -289
  47. package/src/data/bucket/heatmap_bucket.js +0 -17
  48. package/src/data/bucket/line_attributes.js +0 -10
  49. package/src/data/bucket/line_bucket.js +0 -556
  50. package/src/data/bucket/pattern_attributes.js +0 -10
  51. package/src/data/bucket/pattern_bucket_features.js +0 -60
  52. package/src/data/bucket/symbol_attributes.js +0 -117
  53. package/src/data/bucket/symbol_bucket.js +0 -972
  54. package/src/data/bucket.js +0 -123
  55. package/src/data/dem_data.js +0 -125
  56. package/src/data/extent.js +0 -18
  57. package/src/data/feature_index.js +0 -321
  58. package/src/data/feature_position_map.js +0 -125
  59. package/src/data/index_array_type.js +0 -16
  60. package/src/data/load_geometry.js +0 -48
  61. package/src/data/pos_attributes.js +0 -6
  62. package/src/data/program_configuration.js +0 -687
  63. package/src/data/raster_bounds_attributes.js +0 -7
  64. package/src/data/segment.js +0 -76
  65. package/src/geo/edge_insets.js +0 -102
  66. package/src/geo/lng_lat.js +0 -165
  67. package/src/geo/lng_lat_bounds.js +0 -267
  68. package/src/geo/mercator_coordinate.js +0 -153
  69. package/src/geo/transform.js +0 -864
  70. package/src/gl/color_mode.js +0 -34
  71. package/src/gl/context.js +0 -298
  72. package/src/gl/cull_face_mode.js +0 -26
  73. package/src/gl/depth_mode.js +0 -29
  74. package/src/gl/framebuffer.js +0 -44
  75. package/src/gl/index_buffer.js +0 -55
  76. package/src/gl/stencil_mode.js +0 -30
  77. package/src/gl/types.js +0 -84
  78. package/src/gl/value.js +0 -520
  79. package/src/gl/vertex_buffer.js +0 -119
  80. package/src/index.js +0 -201
  81. package/src/render/draw_background.js +0 -57
  82. package/src/render/draw_circle.js +0 -113
  83. package/src/render/draw_collision_debug.js +0 -49
  84. package/src/render/draw_custom.js +0 -49
  85. package/src/render/draw_debug.js +0 -127
  86. package/src/render/draw_fill.js +0 -126
  87. package/src/render/draw_fill_extrusion.js +0 -96
  88. package/src/render/draw_heatmap.js +0 -140
  89. package/src/render/draw_hillshade.js +0 -108
  90. package/src/render/draw_line.js +0 -98
  91. package/src/render/draw_raster.js +0 -125
  92. package/src/render/draw_symbol.js +0 -394
  93. package/src/render/glyph_atlas.js +0 -71
  94. package/src/render/glyph_manager.js +0 -182
  95. package/src/render/image_atlas.js +0 -149
  96. package/src/render/image_manager.js +0 -306
  97. package/src/render/line_atlas.js +0 -210
  98. package/src/render/painter.js +0 -653
  99. package/src/render/program/background_program.js +0 -103
  100. package/src/render/program/circle_program.js +0 -69
  101. package/src/render/program/clipping_mask_program.js +0 -20
  102. package/src/render/program/collision_program.js +0 -49
  103. package/src/render/program/debug_program.js +0 -35
  104. package/src/render/program/fill_extrusion_program.js +0 -122
  105. package/src/render/program/fill_program.js +0 -126
  106. package/src/render/program/heatmap_program.js +0 -83
  107. package/src/render/program/hillshade_program.js +0 -122
  108. package/src/render/program/line_program.js +0 -207
  109. package/src/render/program/pattern.js +0 -102
  110. package/src/render/program/program_uniforms.js +0 -42
  111. package/src/render/program/raster_program.js +0 -92
  112. package/src/render/program/symbol_program.js +0 -224
  113. package/src/render/program.js +0 -168
  114. package/src/render/texture.js +0 -122
  115. package/src/render/uniform_binding.js +0 -147
  116. package/src/render/vertex_array_object.js +0 -163
  117. package/src/shaders/README.md +0 -42
  118. package/src/shaders/_prelude.fragment.glsl +0 -17
  119. package/src/shaders/_prelude.vertex.glsl +0 -73
  120. package/src/shaders/background.fragment.glsl +0 -10
  121. package/src/shaders/background.vertex.glsl +0 -7
  122. package/src/shaders/background_pattern.fragment.glsl +0 -28
  123. package/src/shaders/background_pattern.vertex.glsl +0 -20
  124. package/src/shaders/circle.fragment.glsl +0 -39
  125. package/src/shaders/circle.vertex.glsl +0 -64
  126. package/src/shaders/clipping_mask.fragment.glsl +0 -3
  127. package/src/shaders/clipping_mask.vertex.glsl +0 -7
  128. package/src/shaders/collision_box.fragment.glsl +0 -21
  129. package/src/shaders/collision_box.vertex.glsl +0 -27
  130. package/src/shaders/collision_circle.fragment.glsl +0 -34
  131. package/src/shaders/collision_circle.vertex.glsl +0 -36
  132. package/src/shaders/debug.fragment.glsl +0 -9
  133. package/src/shaders/debug.vertex.glsl +0 -12
  134. package/src/shaders/encode_attribute.js +0 -17
  135. package/src/shaders/fill.fragment.glsl +0 -13
  136. package/src/shaders/fill.vertex.glsl +0 -13
  137. package/src/shaders/fill_extrusion.fragment.glsl +0 -9
  138. package/src/shaders/fill_extrusion.vertex.glsl +0 -66
  139. package/src/shaders/fill_extrusion_pattern.fragment.glsl +0 -45
  140. package/src/shaders/fill_extrusion_pattern.vertex.glsl +0 -79
  141. package/src/shaders/fill_outline.fragment.glsl +0 -17
  142. package/src/shaders/fill_outline.vertex.glsl +0 -17
  143. package/src/shaders/fill_outline_pattern.fragment.glsl +0 -43
  144. package/src/shaders/fill_outline_pattern.vertex.glsl +0 -44
  145. package/src/shaders/fill_pattern.fragment.glsl +0 -36
  146. package/src/shaders/fill_pattern.vertex.glsl +0 -39
  147. package/src/shaders/heatmap.fragment.glsl +0 -22
  148. package/src/shaders/heatmap.vertex.glsl +0 -54
  149. package/src/shaders/heatmap_texture.fragment.glsl +0 -14
  150. package/src/shaders/heatmap_texture.vertex.glsl +0 -11
  151. package/src/shaders/hillshade.fragment.glsl +0 -52
  152. package/src/shaders/hillshade.vertex.glsl +0 -11
  153. package/src/shaders/hillshade_prepare.fragment.glsl +0 -74
  154. package/src/shaders/hillshade_prepare.vertex.glsl +0 -15
  155. package/src/shaders/index.js +0 -20
  156. package/src/shaders/line.fragment.glsl +0 -30
  157. package/src/shaders/line.vertex.glsl +0 -85
  158. package/src/shaders/line_gradient.fragment.glsl +0 -34
  159. package/src/shaders/line_gradient.vertex.glsl +0 -87
  160. package/src/shaders/line_pattern.fragment.glsl +0 -74
  161. package/src/shaders/line_pattern.vertex.glsl +0 -99
  162. package/src/shaders/line_sdf.fragment.glsl +0 -45
  163. package/src/shaders/line_sdf.vertex.glsl +0 -98
  164. package/src/shaders/raster.fragment.glsl +0 -52
  165. package/src/shaders/raster.vertex.glsl +0 -21
  166. package/src/shaders/shaders.js +0 -180
  167. package/src/shaders/symbol_icon.fragment.glsl +0 -17
  168. package/src/shaders/symbol_icon.vertex.glsl +0 -94
  169. package/src/shaders/symbol_sdf.fragment.glsl +0 -52
  170. package/src/shaders/symbol_sdf.vertex.glsl +0 -115
  171. package/src/shaders/symbol_text_and_icon.fragment.glsl +0 -68
  172. package/src/shaders/symbol_text_and_icon.vertex.glsl +0 -116
  173. package/src/source/canvas_source.js +0 -238
  174. package/src/source/geojson_helper.js +0 -92
  175. package/src/source/geojson_source.js +0 -374
  176. package/src/source/geojson_worker_source.js +0 -357
  177. package/src/source/geojson_wrapper.js +0 -94
  178. package/src/source/image_source.js +0 -307
  179. package/src/source/load_tilejson.js +0 -39
  180. package/src/source/mbtiles_source.js +0 -115
  181. package/src/source/offline_database.js +0 -61
  182. package/src/source/offline_database_root.js +0 -62
  183. package/src/source/pixels_to_tile_units.js +0 -21
  184. package/src/source/query_features.js +0 -208
  185. package/src/source/raster_dem_tile_source.js +0 -138
  186. package/src/source/raster_dem_tile_worker_source.js +0 -62
  187. package/src/source/raster_tile_offline_source.js +0 -136
  188. package/src/source/raster_tile_source.js +0 -177
  189. package/src/source/rtl_text_plugin.js +0 -138
  190. package/src/source/source.js +0 -137
  191. package/src/source/source_cache.js +0 -957
  192. package/src/source/source_state.js +0 -159
  193. package/src/source/tile.js +0 -465
  194. package/src/source/tile_bounds.js +0 -38
  195. package/src/source/tile_cache.js +0 -212
  196. package/src/source/tile_id.js +0 -402
  197. package/src/source/vector_tile_source.js +0 -192
  198. package/src/source/vector_tile_worker_source.js +0 -216
  199. package/src/source/video_source.js +0 -203
  200. package/src/source/worker.js +0 -237
  201. package/src/source/worker_source.js +0 -106
  202. package/src/source/worker_tile.js +0 -224
  203. package/src/style/create_style_layer.js +0 -36
  204. package/src/style/evaluation_parameters.js +0 -62
  205. package/src/style/light.js +0 -130
  206. package/src/style/load_glyph_range.js +0 -38
  207. package/src/style/load_sprite.js +0 -67
  208. package/src/style/parse_glyph_pbf.js +0 -44
  209. package/src/style/pauseable_placement.js +0 -132
  210. package/src/style/properties.js +0 -753
  211. package/src/style/query_utils.js +0 -43
  212. package/src/style/style.js +0 -1361
  213. package/src/style/style_glyph.js +0 -17
  214. package/src/style/style_image.js +0 -137
  215. package/src/style/style_layer/background_style_layer.js +0 -21
  216. package/src/style/style_layer/background_style_layer_properties.js +0 -40
  217. package/src/style/style_layer/circle_style_layer.js +0 -98
  218. package/src/style/style_layer/circle_style_layer_properties.js +0 -63
  219. package/src/style/style_layer/custom_style_layer.js +0 -223
  220. package/src/style/style_layer/fill_extrusion_style_layer.js +0 -224
  221. package/src/style/style_layer/fill_extrusion_style_layer_properties.js +0 -50
  222. package/src/style/style_layer/fill_style_layer.js +0 -67
  223. package/src/style/style_layer/fill_style_layer_properties.js +0 -55
  224. package/src/style/style_layer/heatmap_style_layer.js +0 -69
  225. package/src/style/style_layer/heatmap_style_layer_properties.js +0 -44
  226. package/src/style/style_layer/hillshade_style_layer.js +0 -25
  227. package/src/style/style_layer/hillshade_style_layer_properties.js +0 -46
  228. package/src/style/style_layer/layer_properties.js.ejs +0 -69
  229. package/src/style/style_layer/line_style_layer.js +0 -151
  230. package/src/style/style_layer/line_style_layer_properties.js +0 -71
  231. package/src/style/style_layer/raster_style_layer.js +0 -21
  232. package/src/style/style_layer/raster_style_layer_properties.js +0 -50
  233. package/src/style/style_layer/symbol_style_layer.js +0 -190
  234. package/src/style/style_layer/symbol_style_layer_properties.js +0 -153
  235. package/src/style/style_layer/typed_style_layer.js +0 -17
  236. package/src/style/style_layer.js +0 -281
  237. package/src/style/style_layer_index.js +0 -80
  238. package/src/style/validate_style.js +0 -42
  239. package/src/style/zoom_history.js +0 -44
  240. package/src/style-spec/.eslintrc +0 -5
  241. package/src/style-spec/CHANGELOG.md +0 -438
  242. package/src/style-spec/README.md +0 -59
  243. package/src/style-spec/bin/gl-style-composite +0 -9
  244. package/src/style-spec/bin/gl-style-format +0 -22
  245. package/src/style-spec/bin/gl-style-migrate +0 -9
  246. package/src/style-spec/bin/gl-style-validate +0 -50
  247. package/src/style-spec/composite.js +0 -50
  248. package/src/style-spec/declass.js +0 -42
  249. package/src/style-spec/deref.js +0 -52
  250. package/src/style-spec/diff.js +0 -393
  251. package/src/style-spec/dist/.gitkeep +0 -0
  252. package/src/style-spec/empty.js +0 -29
  253. package/src/style-spec/error/parsing_error.js +0 -16
  254. package/src/style-spec/error/validation_error.js +0 -18
  255. package/src/style-spec/expression/compound_expression.js +0 -162
  256. package/src/style-spec/expression/definitions/assertion.js +0 -130
  257. package/src/style-spec/expression/definitions/at.js +0 -70
  258. package/src/style-spec/expression/definitions/case.js +0 -85
  259. package/src/style-spec/expression/definitions/coalesce.js +0 -93
  260. package/src/style-spec/expression/definitions/coercion.js +0 -133
  261. package/src/style-spec/expression/definitions/collator.js +0 -78
  262. package/src/style-spec/expression/definitions/comparison.js +0 -184
  263. package/src/style-spec/expression/definitions/format.js +0 -144
  264. package/src/style-spec/expression/definitions/format_section_override.js +0 -54
  265. package/src/style-spec/expression/definitions/image.js +0 -52
  266. package/src/style-spec/expression/definitions/in.js +0 -92
  267. package/src/style-spec/expression/definitions/index.js +0 -561
  268. package/src/style-spec/expression/definitions/interpolate.js +0 -267
  269. package/src/style-spec/expression/definitions/length.js +0 -61
  270. package/src/style-spec/expression/definitions/let.js +0 -72
  271. package/src/style-spec/expression/definitions/literal.js +0 -77
  272. package/src/style-spec/expression/definitions/match.js +0 -158
  273. package/src/style-spec/expression/definitions/number_format.js +0 -142
  274. package/src/style-spec/expression/definitions/step.js +0 -120
  275. package/src/style-spec/expression/definitions/var.js +0 -46
  276. package/src/style-spec/expression/definitions/within.js +0 -333
  277. package/src/style-spec/expression/evaluation_context.js +0 -59
  278. package/src/style-spec/expression/expression.js +0 -27
  279. package/src/style-spec/expression/index.js +0 -392
  280. package/src/style-spec/expression/is_constant.js +0 -59
  281. package/src/style-spec/expression/parsing_context.js +0 -233
  282. package/src/style-spec/expression/parsing_error.js +0 -13
  283. package/src/style-spec/expression/runtime_error.js +0 -17
  284. package/src/style-spec/expression/scope.js +0 -36
  285. package/src/style-spec/expression/stops.js +0 -39
  286. package/src/style-spec/expression/types/collator.js +0 -61
  287. package/src/style-spec/expression/types/formatted.js +0 -73
  288. package/src/style-spec/expression/types/resolved_image.js +0 -29
  289. package/src/style-spec/expression/types.js +0 -106
  290. package/src/style-spec/expression/values.js +0 -123
  291. package/src/style-spec/feature_filter/README.md +0 -55
  292. package/src/style-spec/feature_filter/convert.js +0 -208
  293. package/src/style-spec/feature_filter/index.js +0 -165
  294. package/src/style-spec/format.js +0 -51
  295. package/src/style-spec/function/convert.js +0 -254
  296. package/src/style-spec/function/index.js +0 -262
  297. package/src/style-spec/group_by_layout.js +0 -75
  298. package/src/style-spec/migrate/expressions.js +0 -39
  299. package/src/style-spec/migrate/v8.js +0 -203
  300. package/src/style-spec/migrate/v9.js +0 -26
  301. package/src/style-spec/migrate.js +0 -36
  302. package/src/style-spec/package.json +0 -41
  303. package/src/style-spec/read_style.js +0 -14
  304. package/src/style-spec/reference/latest.js +0 -3
  305. package/src/style-spec/reference/v8.json +0 -5808
  306. package/src/style-spec/rollup.config.js +0 -45
  307. package/src/style-spec/style-spec.js +0 -122
  308. package/src/style-spec/types.js +0 -438
  309. package/src/style-spec/util/color.js +0 -95
  310. package/src/style-spec/util/color_spaces.js +0 -139
  311. package/src/style-spec/util/deep_equal.js +0 -28
  312. package/src/style-spec/util/extend.js +0 -10
  313. package/src/style-spec/util/get_type.js +0 -17
  314. package/src/style-spec/util/interpolate.js +0 -22
  315. package/src/style-spec/util/properties.js +0 -15
  316. package/src/style-spec/util/ref_properties.js +0 -2
  317. package/src/style-spec/util/result.js +0 -19
  318. package/src/style-spec/util/unbundle_jsonlint.js +0 -24
  319. package/src/style-spec/validate/latest.js +0 -11
  320. package/src/style-spec/validate/validate.js +0 -75
  321. package/src/style-spec/validate/validate_array.js +0 -52
  322. package/src/style-spec/validate/validate_boolean.js +0 -15
  323. package/src/style-spec/validate/validate_color.js +0 -20
  324. package/src/style-spec/validate/validate_constants.js +0 -13
  325. package/src/style-spec/validate/validate_enum.js +0 -21
  326. package/src/style-spec/validate/validate_expression.js +0 -43
  327. package/src/style-spec/validate/validate_filter.js +0 -111
  328. package/src/style-spec/validate/validate_formatted.js +0 -11
  329. package/src/style-spec/validate/validate_function.js +0 -207
  330. package/src/style-spec/validate/validate_glyphs_url.js +0 -21
  331. package/src/style-spec/validate/validate_image.js +0 -11
  332. package/src/style-spec/validate/validate_layer.js +0 -134
  333. package/src/style-spec/validate/validate_layout_property.js +0 -6
  334. package/src/style-spec/validate/validate_light.js +0 -47
  335. package/src/style-spec/validate/validate_number.js +0 -29
  336. package/src/style-spec/validate/validate_object.js +0 -61
  337. package/src/style-spec/validate/validate_paint_property.js +0 -6
  338. package/src/style-spec/validate/validate_property.js +0 -64
  339. package/src/style-spec/validate/validate_source.js +0 -111
  340. package/src/style-spec/validate/validate_string.js +0 -15
  341. package/src/style-spec/validate_mapbox_api_supported.js +0 -171
  342. package/src/style-spec/validate_style.js +0 -39
  343. package/src/style-spec/validate_style.min.js +0 -78
  344. package/src/style-spec/visit.js +0 -77
  345. package/src/symbol/anchor.js +0 -26
  346. package/src/symbol/check_max_angle.js +0 -81
  347. package/src/symbol/clip_line.js +0 -71
  348. package/src/symbol/collision_feature.js +0 -217
  349. package/src/symbol/collision_index.js +0 -372
  350. package/src/symbol/cross_tile_symbol_index.js +0 -301
  351. package/src/symbol/get_anchors.js +0 -167
  352. package/src/symbol/grid_index.js +0 -335
  353. package/src/symbol/mergelines.js +0 -82
  354. package/src/symbol/one_em.js +0 -4
  355. package/src/symbol/opacity_state.js +0 -27
  356. package/src/symbol/placement.js +0 -1062
  357. package/src/symbol/projection.js +0 -450
  358. package/src/symbol/quads.js +0 -334
  359. package/src/symbol/shaping.js +0 -816
  360. package/src/symbol/symbol_layout.js +0 -772
  361. package/src/symbol/symbol_size.js +0 -113
  362. package/src/symbol/transform_text.js +0 -29
  363. package/src/types/callback.js +0 -17
  364. package/src/types/cancelable.js +0 -3
  365. package/src/types/tilejson.js +0 -17
  366. package/src/types/transferable.js +0 -3
  367. package/src/types/window.js +0 -172
  368. package/src/ui/anchor.js +0 -32
  369. package/src/ui/bind_handlers.js +0 -202
  370. package/src/ui/camera.js +0 -1152
  371. package/src/ui/control/attribution_control.js +0 -189
  372. package/src/ui/control/fps_control.js +0 -185
  373. package/src/ui/control/fullscreen_control.js +0 -147
  374. package/src/ui/control/geolocate_control.js +0 -594
  375. package/src/ui/control/logo_control.js +0 -92
  376. package/src/ui/control/navigation_control.js +0 -148
  377. package/src/ui/control/scale_control.js +0 -142
  378. package/src/ui/crs.js +0 -64
  379. package/src/ui/default_locale.js +0 -20
  380. package/src/ui/events.js +0 -806
  381. package/src/ui/handler/box_zoom.js +0 -175
  382. package/src/ui/handler/dblclick_zoom.js +0 -139
  383. package/src/ui/handler/drag_pan.js +0 -416
  384. package/src/ui/handler/drag_rotate.js +0 -378
  385. package/src/ui/handler/keyboard.js +0 -161
  386. package/src/ui/handler/scroll_zoom.js +0 -333
  387. package/src/ui/handler/touch_zoom_rotate.js +0 -293
  388. package/src/ui/hash.js +0 -147
  389. package/src/ui/map.js +0 -2883
  390. package/src/ui/marker.js +0 -607
  391. package/src/ui/offline_map.js +0 -91
  392. package/src/ui/popup.js +0 -530
  393. package/src/util/actor.js +0 -212
  394. package/src/util/ajax.js +0 -371
  395. package/src/util/browser/web_worker.js +0 -10
  396. package/src/util/browser/window.js +0 -5
  397. package/src/util/browser.js +0 -70
  398. package/src/util/classify_rings.js +0 -52
  399. package/src/util/color_ramp.js +0 -28
  400. package/src/util/config.js +0 -30
  401. package/src/util/debug.js +0 -12
  402. package/src/util/dictionary_coder.js +0 -30
  403. package/src/util/dispatcher.js +0 -70
  404. package/src/util/dom.js +0 -144
  405. package/src/util/evented.js +0 -174
  406. package/src/util/find_pole_of_inaccessibility.js +0 -129
  407. package/src/util/global_worker_pool.js +0 -17
  408. package/src/util/image.js +0 -142
  409. package/src/util/intersection_tests.js +0 -208
  410. package/src/util/is_char_in_unicode_block.js +0 -311
  411. package/src/util/mapbox.js +0 -486
  412. package/src/util/offscreen_canvas_supported.js +0 -14
  413. package/src/util/performance.js +0 -112
  414. package/src/util/primitives.js +0 -145
  415. package/src/util/resolve_tokens.js +0 -16
  416. package/src/util/script_detection.js +0 -328
  417. package/src/util/sku_token.js +0 -42
  418. package/src/util/smart_wrap.js +0 -55
  419. package/src/util/struct_array.js +0 -243
  420. package/src/util/struct_array.js.ejs +0 -112
  421. package/src/util/struct_array_layout.js.ejs +0 -98
  422. package/src/util/task_queue.js +0 -68
  423. package/src/util/throttle.js +0 -28
  424. package/src/util/throttled_invoker.js +0 -46
  425. package/src/util/tile_cover.js +0 -101
  426. package/src/util/tile_request_cache.js +0 -172
  427. package/src/util/util.js +0 -504
  428. package/src/util/vectortile_to_geojson.js +0 -54
  429. package/src/util/verticalize_punctuation.js +0 -114
  430. package/src/util/web_worker.js +0 -91
  431. package/src/util/web_worker_transfer.js +0 -266
  432. package/src/util/webp_supported.js +0 -69
  433. package/src/util/window.js +0 -102
  434. package/src/util/worker_pool.js +0 -47
package/src/ui/map.js DELETED
@@ -1,2883 +0,0 @@
1
- // @flow
2
-
3
- import {version} from '../../package.json';
4
- import {extend, bindAll, warnOnce, uniqueId} from '../util/util';
5
- import browser from '../util/browser';
6
- import window from '../util/window';
7
- const {HTMLImageElement, HTMLElement, ImageBitmap} = window;
8
- import DOM from '../util/dom';
9
- import {getImage, getJSON, ResourceType} from '../util/ajax';
10
- import {RequestManager} from '../util/mapbox';
11
- import Style from '../style/style';
12
- import EvaluationParameters from '../style/evaluation_parameters';
13
- import Painter from '../render/painter';
14
- import Transform from '../geo/transform';
15
- import Hash from './hash';
16
- import bindHandlers from './bind_handlers';
17
- import Camera from './camera';
18
- import LngLat from '../geo/lng_lat';
19
- import LngLatBounds from '../geo/lng_lat_bounds';
20
- import Point from '@mapbox/point-geometry';
21
- import AttributionControl from './control/attribution_control';
22
- import LogoControl from './control/logo_control';
23
- import isSupported from '@mapbox/mapbox-gl-supported';
24
- import {RGBAImage} from '../util/image';
25
- import {Event, ErrorEvent} from '../util/evented';
26
- import {MapMouseEvent} from './events';
27
- import TaskQueue from '../util/task_queue';
28
- import webpSupported from '../util/webp_supported';
29
- import {PerformanceMarkers, PerformanceUtils} from '../util/performance';
30
-
31
- import {setCacheLimits} from '../util/tile_request_cache';
32
-
33
- import CRS from './crs';
34
- import {CanonicalTileID} from '../source/tile_id';
35
- import TileBounds from '../source/tile_bounds';
36
- import GeoJSONFeature from '../util/vectortile_to_geojson';
37
- import GeoJSONSource from '../source/geojson_source';
38
- import VectorTileSource from '../source/vector_tile_source';
39
- import RasterTileSource from '../source/raster_tile_source';
40
- import MercatorCoordinate, {
41
- latFromMercatorY,
42
- mercatorXfromLng,
43
- mercatorYfromLat,
44
- mercatorZfromAltitude
45
- } from '../geo/mercator_coordinate';
46
-
47
- import type {PointLike} from '@mapbox/point-geometry';
48
- import type {RequestTransformFunction} from '../util/mapbox';
49
- import type {LngLatLike} from '../geo/lng_lat';
50
- import type {LngLatBoundsLike} from '../geo/lng_lat_bounds';
51
- import type {StyleOptions, StyleSetterOptions} from '../style/style';
52
- import type {MapEvent, MapDataEvent} from './events';
53
- import type {CustomLayerInterface} from '../style/style_layer/custom_style_layer';
54
- import type {StyleImageInterface, StyleImageMetadata} from '../style/style_image';
55
-
56
- import type ScrollZoomHandler from './handler/scroll_zoom';
57
- import type BoxZoomHandler from './handler/box_zoom';
58
- import type DragRotateHandler from './handler/drag_rotate';
59
- import type DragPanHandler, {DragPanOptions} from './handler/drag_pan';
60
- import type KeyboardHandler from './handler/keyboard';
61
- import type DoubleClickZoomHandler from './handler/dblclick_zoom';
62
- import type TouchZoomRotateHandler from './handler/touch_zoom_rotate';
63
- import defaultLocale from './default_locale';
64
- import type {TaskID} from '../util/task_queue';
65
- import type {Cancelable} from '../types/cancelable';
66
- import type {
67
- LayerSpecification,
68
- FilterSpecification,
69
- StyleSpecification,
70
- LightSpecification,
71
- SourceSpecification
72
- } from '../style-spec/types';
73
-
74
- type ControlPosition = 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';
75
- /* eslint-disable no-use-before-define */
76
- type IControl = {
77
- onAdd(map: Map): HTMLElement;
78
- onRemove(map: Map): void;
79
-
80
- +getDefaultPosition?: () => ControlPosition;
81
- }
82
- /* eslint-enable no-use-before-define */
83
-
84
- type MapOptions = {
85
- hash?: boolean | string,
86
- interactive?: boolean,
87
- container: HTMLElement | string,
88
- bearingSnap?: number,
89
- attributionControl?: boolean,
90
- customAttribution?: string | Array<string>,
91
- logoPosition?: ControlPosition,
92
- failIfMajorPerformanceCaveat?: boolean,
93
- preserveDrawingBuffer?: boolean,
94
- antialias?: boolean,
95
- refreshExpiredTiles?: boolean,
96
- maxBounds?: LngLatBoundsLike,
97
- scrollZoom?: boolean,
98
- minZoom?: ?number,
99
- maxZoom?: ?number,
100
- minPitch?: ?number,
101
- maxPitch?: ?number,
102
- boxZoom?: boolean,
103
- dragRotate?: boolean,
104
- dragPan?: DragPanOptions,
105
- keyboard?: boolean,
106
- doubleClickZoom?: boolean,
107
- touchZoomRotate?: boolean,
108
- trackResize?: boolean,
109
- center?: LngLatLike,
110
- zoom?: number,
111
- bearing?: number,
112
- pitch?: number,
113
- renderWorldCopies?: boolean,
114
- maxTileCacheSize?: number,
115
- transformRequest?: RequestTransformFunction,
116
- accessToken: string,
117
- locale?: Object,
118
- crs?: string,
119
- };
120
-
121
- const defaultMinZoom = -2;
122
- const defaultMaxZoom = 22;
123
-
124
- // the default values, but also the valid range
125
- const defaultMinPitch = 0;
126
- const defaultMaxPitch = 60;
127
-
128
- const defaultOptions = {
129
- center: [0, 0],
130
- zoom: 0,
131
- bearing: 0,
132
- pitch: 0,
133
-
134
- minZoom: defaultMinZoom,
135
- maxZoom: defaultMaxZoom,
136
-
137
- minPitch: defaultMinPitch,
138
- maxPitch: defaultMaxPitch,
139
-
140
- interactive: true,
141
- scrollZoom: true,
142
- boxZoom: true,
143
- dragRotate: true,
144
- dragPan: true,
145
- keyboard: true,
146
- doubleClickZoom: true,
147
- touchZoomRotate: true,
148
-
149
- bearingSnap: 7,
150
- clickTolerance: 3,
151
-
152
- hash: false,
153
- attributionControl: true,
154
-
155
- failIfMajorPerformanceCaveat: false,
156
- preserveDrawingBuffer: false,
157
- trackResize: true,
158
- renderWorldCopies: true,
159
- refreshExpiredTiles: true,
160
- maxTileCacheSize: null,
161
- localIdeographFontFamily: 'sans-serif',
162
- transformRequest: null,
163
- accessToken: null,
164
- fadeDuration: 300,
165
- crossSourceCollisions: true
166
- };
167
-
168
- /**
169
- * The `Map` object represents the map on your page. It exposes methods
170
- * and properties that enable you to programmatically change the map,
171
- * and fires events as users interact with it.
172
- *
173
- * You create a `Map` by specifying a `container` and other options.
174
- * Then Mapbox GL JS initializes the map on the page and returns your `Map`
175
- * object.
176
- *
177
- * @extends Evented
178
- * @param {Object} options
179
- * @param {HTMLElement|string} options.container The HTML element in which Mapbox GL JS will render the map, or the element's string `id`. The specified element must have no children.
180
- * @param {number} [options.minZoom=0] The minimum zoom level of the map (0-24).
181
- * @param {number} [options.maxZoom=22] The maximum zoom level of the map (0-24).
182
- * @param {number} [options.minPitch=0] The minimum pitch of the map (0-60).
183
- * @param {number} [options.maxPitch=60] The maximum pitch of the map (0-60).
184
- * @param {Object|string} [options.style] The map's Mapbox style. This must be an a JSON object conforming to
185
- * the schema described in the [Mapbox Style Specification](https://mapbox.com/mapbox-gl-style-spec/), or a URL to
186
- * such JSON.
187
- *
188
- * To load a style from the Mapbox API, you can use a URL of the form `mapbox://styles/:owner/:style`,
189
- * where `:owner` is your Mapbox account name and `:style` is the style ID. Or you can use one of the following
190
- * [the predefined Mapbox styles](https://www.mapbox.com/maps/):
191
- *
192
- * * `mapbox://styles/mapbox/streets-v11`
193
- * * `mapbox://styles/mapbox/outdoors-v11`
194
- * * `mapbox://styles/mapbox/light-v10`
195
- * * `mapbox://styles/mapbox/dark-v10`
196
- * * `mapbox://styles/mapbox/satellite-v9`
197
- * * `mapbox://styles/mapbox/satellite-streets-v11`
198
- * * `mapbox://styles/mapbox/navigation-preview-day-v4`
199
- * * `mapbox://styles/mapbox/navigation-preview-night-v4`
200
- * * `mapbox://styles/mapbox/navigation-guidance-day-v4`
201
- * * `mapbox://styles/mapbox/navigation-guidance-night-v4`
202
- *
203
- * Tilesets hosted with Mapbox can be style-optimized if you append `?optimize=true` to the end of your style URL, like `mapbox://styles/mapbox/streets-v11?optimize=true`.
204
- * Learn more about style-optimized vector tiles in our [API documentation](https://www.mapbox.com/api-documentation/maps/#retrieve-tiles).
205
- *
206
- * @param {(boolean|string)} [options.hash=false] If `true`, the map's position (zoom, center latitude, center longitude, bearing, and pitch) will be synced with the hash fragment of the page's URL.
207
- * For example, `http://path/to/my/page.html#2.59/39.26/53.07/-24.1/60`.
208
- * An additional string may optionally be provided to indicate a parameter-styled hash,
209
- * e.g. http://path/to/my/page.html#map=2.59/39.26/53.07/-24.1/60&foo=bar, where foo
210
- * is a custom parameter and bar is an arbitrary hash distinct from the map hash.
211
- * @param {boolean} [options.interactive=true] If `false`, no mouse, touch, or keyboard listeners will be attached to the map, so it will not respond to interaction.
212
- * @param {number} [options.bearingSnap=7] The threshold, measured in degrees, that determines when the map's
213
- * bearing will snap to north. For example, with a `bearingSnap` of 7, if the user rotates
214
- * the map within 7 degrees of north, the map will automatically snap to exact north.
215
- * @param {boolean} [options.pitchWithRotate=true] If `false`, the map's pitch (tilt) control with "drag to rotate" interaction will be disabled.
216
- * @param {number} [options.clickTolerance=3] The max number of pixels a user can shift the mouse pointer during a click for it to be considered a valid click (as opposed to a mouse drag).
217
- * @param {boolean} [options.attributionControl=true] If `true`, an {@link AttributionControl} will be added to the map.
218
- * @param {string | Array<string>} [options.customAttribution] String or strings to show in an {@link AttributionControl}. Only applicable if `options.attributionControl` is `true`.
219
- * @param {string} [options.logoPosition='bottom-left'] A string representing the position of the Mapbox wordmark on the map. Valid options are `top-left`,`top-right`, `bottom-left`, `bottom-right`.
220
- * @param {boolean} [options.failIfMajorPerformanceCaveat=false] If `true`, map creation will fail if the performance of Mapbox
221
- * GL JS would be dramatically worse than expected (i.e. a software renderer would be used).
222
- * @param {boolean} [options.preserveDrawingBuffer=false] If `true`, the map's canvas can be exported to a PNG using `map.getCanvas().toDataURL()`. This is `false` by default as a performance optimization.
223
- * @param {boolean} [options.antialias] If `true`, the gl context will be created with MSAA antialiasing, which can be useful for antialiasing custom layers. this is `false` by default as a performance optimization.
224
- * @param {boolean} [options.refreshExpiredTiles=true] If `false`, the map won't attempt to re-request tiles once they expire per their HTTP `cacheControl`/`expires` headers.
225
- * @param {LngLatBoundsLike} [options.maxBounds] If set, the map will be constrained to the given bounds.
226
- * @param {boolean|Object} [options.scrollZoom=true] If `true`, the "scroll to zoom" interaction is enabled. An `Object` value is passed as options to {@link ScrollZoomHandler#enable}.
227
- * @param {boolean} [options.boxZoom=true] If `true`, the "box zoom" interaction is enabled (see {@link BoxZoomHandler}).
228
- * @param {boolean} [options.dragRotate=true] If `true`, the "drag to rotate" interaction is enabled (see {@link DragRotateHandler}).
229
- * @param {boolean|Object} [options.dragPan=true] If `true`, the "drag to pan" interaction is enabled. An `Object` value is passed as options to {@link DragPanHandler#enable}.
230
- * @param {boolean} [options.keyboard=true] If `true`, keyboard shortcuts are enabled (see {@link KeyboardHandler}).
231
- * @param {boolean} [options.doubleClickZoom=true] If `true`, the "double click to zoom" interaction is enabled (see {@link DoubleClickZoomHandler}).
232
- * @param {boolean|Object} [options.touchZoomRotate=true] If `true`, the "pinch to rotate and zoom" interaction is enabled. An `Object` value is passed as options to {@link TouchZoomRotateHandler#enable}.
233
- * @param {boolean} [options.trackResize=true] If `true`, the map will automatically resize when the browser window resizes.
234
- * @param {LngLatLike} [options.center=[0, 0]] The inital geographical centerpoint of the map. If `center` is not specified in the constructor options, Mapbox GL JS will look for it in the map's style object. If it is not specified in the style, either, it will default to `[0, 0]` Note: Mapbox GL uses longitude, latitude coordinate order (as opposed to latitude, longitude) to match GeoJSON.
235
- * @param {number} [options.zoom=0] The initial zoom level of the map. If `zoom` is not specified in the constructor options, Mapbox GL JS will look for it in the map's style object. If it is not specified in the style, either, it will default to `0`.
236
- * @param {number} [options.bearing=0] The initial bearing (rotation) of the map, measured in degrees counter-clockwise from north. If `bearing` is not specified in the constructor options, Mapbox GL JS will look for it in the map's style object. If it is not specified in the style, either, it will default to `0`.
237
- * @param {number} [options.pitch=0] The initial pitch (tilt) of the map, measured in degrees away from the plane of the screen (0-60). If `pitch` is not specified in the constructor options, Mapbox GL JS will look for it in the map's style object. If it is not specified in the style, either, it will default to `0`.
238
- * @param {LngLatBoundsLike} [options.bounds] The initial bounds of the map. If `bounds` is specified, it overrides `center` and `zoom` constructor options.
239
- * @param {Object} [options.fitBoundsOptions] A [`fitBounds`](#map#fitbounds) options object to use _only_ when fitting the initial `bounds` provided above.
240
- * @param {boolean} [options.renderWorldCopies=true] If `true`, multiple copies of the world will be rendered side by side beyond -180 and 180 degrees longitude. If set to `false`:
241
- * - When the map is zoomed out far enough that a single representation of the world does not fill the map's entire
242
- * container, there will be blank space beyond 180 and -180 degrees longitude.
243
- * - Features that cross 180 and -180 degrees longitude will be cut in two (with one portion on the right edge of the
244
- * map and the other on the left edge of the map) at every zoom level.
245
- * @param {number} [options.maxTileCacheSize=null] The maximum number of tiles stored in the tile cache for a given source. If omitted, the cache will be dynamically sized based on the current viewport.
246
- * @param {string} [options.localIdeographFontFamily='sans-serif'] Defines a CSS
247
- * font-family for locally overriding generation of glyphs in the 'CJK Unified Ideographs', 'Hiragana', 'Katakana' and 'Hangul Syllables' ranges.
248
- * In these ranges, font settings from the map's style will be ignored, except for font-weight keywords (light/regular/medium/bold).
249
- * Set to `false`, to enable font settings from the map's style for these glyph ranges. Note that [Mapbox Studio](https://studio.mapbox.com/) sets this value to `false` by default.
250
- * The purpose of this option is to avoid bandwidth-intensive glyph server requests. (See [Use locally generated ideographs](https://www.mapbox.com/mapbox-gl-js/example/local-ideographs).)
251
- * @param {RequestTransformFunction} [options.transformRequest=null] A callback run before the Map makes a request for an external URL. The callback can be used to modify the url, set headers, or set the credentials property for cross-origin requests.
252
- * Expected to return an object with a `url` property and optionally `headers` and `credentials` properties.
253
- * @param {boolean} [options.collectResourceTiming=false] If `true`, Resource Timing API information will be collected for requests made by GeoJSON and Vector Tile web workers (this information is normally inaccessible from the main Javascript thread). Information will be returned in a `resourceTiming` property of relevant `data` events.
254
- * @param {number} [options.fadeDuration=300] Controls the duration of the fade-in/fade-out animation for label collisions, in milliseconds. This setting affects all symbol layers. This setting does not affect the duration of runtime styling transitions or raster tile cross-fading.
255
- * @param {boolean} [options.crossSourceCollisions=true] If `true`, symbols from multiple sources can collide with each other during collision detection. If `false`, collision detection is run separately for the symbols in each source.
256
- * @param {string} [options.accessToken=null] If specified, map will use this token instead of the one defined in mapboxgl.accessToken.
257
- * @param {string} [options.locale=null] A patch to apply to the default localization table for UI strings, e.g. control tooltips. The `locale` object maps namespaced UI string IDs to translated strings in the target language; see `src/ui/default_locale.js` for an example with all supported string IDs. The object may specify all UI strings (thereby adding support for a new translation) or only a subset of strings (thereby patching the default translation table).
258
- * @example
259
- * var map = new mapboxgl.Map({
260
- * container: 'map',
261
- * center: [-122.420679, 37.772537],
262
- * zoom: 13,
263
- * style: style_object,
264
- * hash: true,
265
- * transformRequest: (url, resourceType)=> {
266
- * if(resourceType === 'Source' && url.startsWith('http://myHost')) {
267
- * return {
268
- * url: url.replace('http', 'https'),
269
- * headers: { 'my-custom-header': true},
270
- * credentials: 'include' // Include cookies for cross-origin requests
271
- * }
272
- * }
273
- * }
274
- * });
275
- * @see [Display a map](https://www.mapbox.com/mapbox-gl-js/examples/)
276
- */
277
- class Map extends Camera {
278
- style: Style;
279
- painter: Painter;
280
-
281
- _container: HTMLElement;
282
- _missingCSSCanary: HTMLElement;
283
- _canvasContainer: HTMLElement;
284
- _controlContainer: HTMLElement;
285
- _controlPositions: {[_: string]: HTMLElement};
286
- _interactive: ?boolean;
287
- _showTileBoundaries: ?boolean;
288
- _showCollisionBoxes: ?boolean;
289
- _showPadding: ?boolean;
290
- _showOverdrawInspector: boolean;
291
- _repaint: ?boolean;
292
- _vertices: ?boolean;
293
- _canvas: HTMLCanvasElement;
294
- _maxTileCacheSize: number;
295
- _frame: ?Cancelable;
296
- _styleDirty: ?boolean;
297
- _sourcesDirty: ?boolean;
298
- _placementDirty: ?boolean;
299
- _loaded: boolean;
300
- // accounts for placement finishing as well
301
- _fullyLoaded: boolean;
302
- _trackResize: boolean;
303
- _preserveDrawingBuffer: boolean;
304
- _failIfMajorPerformanceCaveat: boolean;
305
- _antialias: boolean;
306
- _refreshExpiredTiles: boolean;
307
- _hash: Hash;
308
- _delegatedListeners: any;
309
- _fadeDuration: number;
310
- _crossSourceCollisions: boolean;
311
- _crossFadingFactor: number;
312
- _collectResourceTiming: boolean;
313
- _renderTaskQueue: TaskQueue;
314
- _controls: Array<IControl>;
315
- _mapId: number;
316
- _localIdeographFontFamily: string;
317
- _requestManager: RequestManager;
318
- _locale: Object;
319
-
320
- /**
321
- * The map's {@link ScrollZoomHandler}, which implements zooming in and out with a scroll wheel or trackpad.
322
- * Find more details and examples using `scrollZoom` in the {@link ScrollZoomHandler} section.
323
- */
324
- scrollZoom: ScrollZoomHandler;
325
-
326
- /**
327
- * The map's {@link BoxZoomHandler}, which implements zooming using a drag gesture with the Shift key pressed.
328
- * Find more details and examples using `boxZoom` in the {@link BoxZoomHandler} section.
329
- */
330
- boxZoom: BoxZoomHandler;
331
-
332
- /**
333
- * The map's {@link DragRotateHandler}, which implements rotating the map while dragging with the right
334
- * mouse button or with the Control key pressed. Find more details and examples using `dragRotate`
335
- * in the {@link DragRotateHandler} section.
336
- */
337
- dragRotate: DragRotateHandler;
338
-
339
- /**
340
- * The map's {@link DragPanHandler}, which implements dragging the map with a mouse or touch gesture.
341
- * Find more details and examples using `dragPan` in the {@link DragPanHandler} section.
342
- */
343
- dragPan: DragPanHandler;
344
-
345
- /**
346
- * The map's {@link KeyboardHandler}, which allows the user to zoom, rotate, and pan the map using keyboard
347
- * shortcuts. Find more details and examples using `keyboard` in the {@link KeyboardHandler} section.
348
- */
349
- keyboard: KeyboardHandler;
350
-
351
- /**
352
- * The map's {@link DoubleClickZoomHandler}, which allows the user to zoom by double clicking.
353
- * Find more details and examples using `doubleClickZoom` in the {@link DoubleClickZoomHandler} section.
354
- */
355
- doubleClickZoom: DoubleClickZoomHandler;
356
-
357
- /**
358
- * The map's {@link TouchZoomRotateHandler}, which allows the user to zoom or rotate the map with touch gestures.
359
- * Find more details and examples using `touchZoomRotate` in the {@link TouchZoomRotateHandler} section.
360
- */
361
- touchZoomRotate: TouchZoomRotateHandler;
362
-
363
- overlayLayersManager:Object
364
-
365
- constructor(options: MapOptions) {
366
- PerformanceUtils.mark(PerformanceMarkers.create);
367
-
368
- options = extend({}, defaultOptions, options);
369
-
370
- if (options.minZoom != null && options.maxZoom != null && options.minZoom > options.maxZoom) {
371
- throw new Error(`maxZoom must be greater than or equal to minZoom`);
372
- }
373
-
374
- if (options.minPitch != null && options.maxPitch != null && options.minPitch > options.maxPitch) {
375
- throw new Error(`maxPitch must be greater than or equal to minPitch`);
376
- }
377
-
378
- if (options.minPitch != null && options.minPitch < defaultMinPitch) {
379
- throw new Error(`minPitch must be greater than or equal to ${defaultMinPitch}`);
380
- }
381
-
382
- if (options.maxPitch != null && options.maxPitch > defaultMaxPitch) {
383
- throw new Error(`maxPitch must be less than or equal to ${defaultMaxPitch}`);
384
- }
385
-
386
- const transform = new Transform(options.minZoom, options.maxZoom, options.minPitch, options.maxPitch, options.renderWorldCopies);
387
- super(transform, options);
388
-
389
- //增加crs属性
390
- this.crs = this.initCRS(options.crs);
391
- this.setCRS(this.crs);
392
-
393
- this._interactive = options.interactive;
394
- this._maxTileCacheSize = options.maxTileCacheSize;
395
- this._failIfMajorPerformanceCaveat = options.failIfMajorPerformanceCaveat;
396
- this._preserveDrawingBuffer = options.preserveDrawingBuffer;
397
- this._antialias = options.antialias;
398
- this._trackResize = options.trackResize;
399
- this._bearingSnap = options.bearingSnap;
400
- this._refreshExpiredTiles = options.refreshExpiredTiles;
401
- this._fadeDuration = options.fadeDuration;
402
- this._crossSourceCollisions = options.crossSourceCollisions;
403
- this._crossFadingFactor = 1;
404
- this._collectResourceTiming = options.collectResourceTiming;
405
- this._renderTaskQueue = new TaskQueue();
406
- this._controls = [];
407
- this._mapId = uniqueId();
408
- this._locale = extend({}, defaultLocale, options.locale);
409
-
410
- this._requestManager = new RequestManager(options.transformRequest, options.accessToken);
411
-
412
- if (typeof options.container === 'string') {
413
- this._container = window.document.getElementById(options.container);
414
- if (!this._container) {
415
- throw new Error(`Container '${options.container}' not found.`);
416
- }
417
- } else if (options.container instanceof HTMLElement) {
418
- this._container = options.container;
419
- } else {
420
- throw new Error(`Invalid type: 'container' must be a String or HTMLElement.`);
421
- }
422
-
423
- if (options.maxBounds) {
424
- this.setMaxBounds(options.maxBounds);
425
- }
426
-
427
- bindAll([
428
- '_onWindowOnline',
429
- '_onWindowResize',
430
- '_contextLost',
431
- '_contextRestored'
432
- ], this);
433
-
434
- this._setupContainer();
435
- this._setupPainter();
436
- if (this.painter === undefined) {
437
- throw new Error(`Failed to initialize WebGL.`);
438
- }
439
-
440
- this.on('move', () => this._update(false));
441
- this.on('moveend', () => this._update(false));
442
- this.on('zoom', () => this._update(true));
443
-
444
- if (typeof window !== 'undefined') {
445
- window.addEventListener('online', this._onWindowOnline, false);
446
- window.addEventListener('resize', this._onWindowResize, false);
447
- }
448
-
449
- bindHandlers(this, options);
450
-
451
- const hashName = (typeof options.hash === 'string' && options.hash) || undefined;
452
- this._hash = options.hash && (new Hash(hashName)).addTo(this);
453
- // don't set position from options if set through hash
454
- if (!this._hash || !this._hash._onHashChange()) {
455
- this.jumpTo({
456
- center: options.center,
457
- zoom: options.zoom,
458
- bearing: options.bearing,
459
- pitch: options.pitch
460
- });
461
-
462
- if (options.bounds) {
463
- this.resize();
464
- this.fitBounds(options.bounds, extend({}, options.fitBoundsOptions, {duration: 0}));
465
- }
466
- }
467
-
468
- this.resize();
469
-
470
- this._localIdeographFontFamily = options.localIdeographFontFamily;
471
- if (options.style) this.setStyle(options.style, {localIdeographFontFamily: options.localIdeographFontFamily});
472
-
473
- if (options.attributionControl)
474
- this.addControl(new AttributionControl({customAttribution: options.customAttribution}));
475
-
476
- this.addControl(new LogoControl(), options.logoPosition);
477
-
478
- this.on('style.load', () => {
479
- if (this.transform.unmodified) {
480
- this.jumpTo((this.style.stylesheet: any));
481
- }
482
- });
483
- this.on('data', (event: MapDataEvent) => {
484
- this._update(event.dataType === 'style');
485
- this.fire(new Event(`${event.dataType}data`, event));
486
- });
487
- this.on('dataloading', (event: MapDataEvent) => {
488
- this.fire(new Event(`${event.dataType}dataloading`, event));
489
- });
490
-
491
- this.overlayLayersManager={}
492
- }
493
-
494
- /*
495
- * Returns a unique number for this map instance which is used for the MapLoadEvent
496
- * to make sure we only fire one event per instantiated map object.
497
- * @private
498
- * @returns {number}
499
- */
500
- _getMapId() {
501
- return this._mapId;
502
- }
503
-
504
- /**
505
- * Adds an {@link IControl} to the map, calling `control.onAdd(this)`.
506
- *
507
- * @param {IControl} control The {@link IControl} to add.
508
- * @param {string} [position] position on the map to which the control will be added.
509
- * Valid values are `'top-left'`, `'top-right'`, `'bottom-left'`, and `'bottom-right'`. Defaults to `'top-right'`.
510
- * @returns {Map} `this`
511
- * @example
512
- * // Add zoom and rotation controls to the map.
513
- * map.addControl(new mapboxgl.NavigationControl());
514
- * @see [Display map navigation controls](https://www.mapbox.com/mapbox-gl-js/example/navigation/)
515
- */
516
- addControl(control: IControl, position?: ControlPosition) {
517
- if (position === undefined && control.getDefaultPosition) {
518
- position = control.getDefaultPosition();
519
- }
520
- if (position === undefined) {
521
- position = 'top-right';
522
- }
523
- if (!control || !control.onAdd) {
524
- return this.fire(new ErrorEvent(new Error(
525
- 'Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.')));
526
- }
527
- const controlElement = control.onAdd(this);
528
- this._controls.push(control);
529
-
530
- const positionContainer = this._controlPositions[position];
531
- if (position.indexOf('bottom') !== -1) {
532
- positionContainer.insertBefore(controlElement, positionContainer.firstChild);
533
- } else {
534
- positionContainer.appendChild(controlElement);
535
- }
536
- return this;
537
- }
538
-
539
- /**
540
- * Removes the control from the map.
541
- *
542
- * @param {IControl} control The {@link IControl} to remove.
543
- * @returns {Map} `this`
544
- * @example
545
- * // Define a new navigation control.
546
- * var navigation = new mapboxgl.NavigationControl();
547
- * // Add zoom and rotation controls to the map.
548
- * map.addControl(navigation);
549
- * // Remove zoom and rotation controls from the map.
550
- * map.removeControl(navigation);
551
- */
552
- removeControl(control: IControl) {
553
- if (!control || !control.onRemove) {
554
- return this.fire(new ErrorEvent(new Error(
555
- 'Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.')));
556
- }
557
- const ci = this._controls.indexOf(control);
558
- if (ci > -1) this._controls.splice(ci, 1);
559
- control.onRemove(this);
560
- return this;
561
- }
562
-
563
- /**
564
- * Resizes the map according to the dimensions of its
565
- * `container` element.
566
- *
567
- * Checks if the map container size changed and updates the map if it has changed.
568
- * This method must be called after the map's `container` is resized programmatically
569
- * or when the map is shown after being initially hidden with CSS.
570
- *
571
- * @param eventData Additional properties to be passed to `movestart`, `move`, `resize`, and `moveend`
572
- * events that get triggered as a result of resize. This can be useful for differentiating the
573
- * source of an event (for example, user-initiated or programmatically-triggered events).
574
- * @returns {Map} `this`
575
- * @example
576
- * // Resize the map when the map container is shown
577
- * // after being initially hidden with CSS.
578
- * var mapDiv = document.getElementById('map');
579
- * if (mapDiv.style.visibility === true) map.resize();
580
- */
581
- resize(eventData?: Object) {
582
- const dimensions = this._containerDimensions();
583
- const width = dimensions[0];
584
- const height = dimensions[1];
585
-
586
- this._resizeCanvas(width, height);
587
- this.transform.resize(width, height);
588
- this.painter.resize(width, height);
589
-
590
- this.fire(new Event('movestart', eventData))
591
- .fire(new Event('move', eventData))
592
- .fire(new Event('resize', eventData))
593
- .fire(new Event('moveend', eventData));
594
- return this;
595
- }
596
-
597
- /**
598
- * Returns the map's geographical bounds. When the bearing or pitch is non-zero, the visible region is not
599
- * an axis-aligned rectangle, and the result is the smallest bounds that encompasses the visible region.
600
- * @returns {LngLatBounds} The geographical bounds of the map as {@link LngLatBounds}.
601
- * @example
602
- * var bounds = map.getBounds();
603
- */
604
- getBounds(): LngLatBounds {
605
- return this.transform.getBounds();
606
- }
607
-
608
- /**
609
- * Returns the maximum geographical bounds the map is constrained to, or `null` if none set.
610
- * @returns The map object.
611
- * @example
612
- * var maxBounds = map.getMaxBounds();
613
- */
614
- getMaxBounds(): LngLatBounds | null {
615
- return this.transform.getMaxBounds();
616
- }
617
-
618
- /**
619
- * Sets or clears the map's geographical bounds.
620
- *
621
- * Pan and zoom operations are constrained within these bounds.
622
- * If a pan or zoom is performed that would
623
- * display regions outside these bounds, the map will
624
- * instead display a position and zoom level
625
- * as close as possible to the operation's request while still
626
- * remaining within the bounds.
627
- *
628
- * @param {LngLatBoundsLike | null | undefined} bounds The maximum bounds to set. If `null` or `undefined` is provided, the function removes the map's maximum bounds.
629
- * @returns {Map} `this`
630
- * @example
631
- * // Define bounds that conform to the `LngLatBoundsLike` object.
632
- * var bounds = [
633
- * [-74.04728, 40.68392], // [west, south]
634
- * [-73.91058, 40.87764] // [east, north]
635
- * ];
636
- * // Set the map's max bounds.
637
- * map.setMaxBounds(bounds);
638
- */
639
- setMaxBounds(bounds: LngLatBoundsLike) {
640
- this.transform.setMaxBounds(LngLatBounds.convert(bounds));
641
- return this._update();
642
- }
643
-
644
- /**
645
- * Sets or clears the map's minimum zoom level.
646
- * If the map's current zoom level is lower than the new minimum,
647
- * the map will zoom to the new minimum.
648
- *
649
- * It is not always possible to zoom out and reach the set `minZoom`.
650
- * Other factors such as map height may restrict zooming. For example,
651
- * if the map is 512px tall it will not be possible to zoom below zoom 0
652
- * no matter what the `minZoom` is set to.
653
- *
654
- * @param {number | null | undefined} minZoom The minimum zoom level to set (-2 - 24).
655
- * If `null` or `undefined` is provided, the function removes the current minimum zoom (i.e. sets it to -2).
656
- * @returns {Map} `this`
657
- * @example
658
- * map.setMinZoom(12.25);
659
- */
660
- setMinZoom(minZoom?: ?number) {
661
-
662
- minZoom = minZoom === null || minZoom === undefined ? defaultMinZoom : minZoom;
663
-
664
- if (minZoom >= defaultMinZoom && minZoom <= this.transform.maxZoom) {
665
- this.transform.minZoom = minZoom;
666
- this._update();
667
-
668
- if (this.getZoom() < minZoom) this.setZoom(minZoom);
669
-
670
- return this;
671
-
672
- } else throw new Error(`minZoom must be between ${defaultMinZoom} and the current maxZoom, inclusive`);
673
- }
674
-
675
- /**
676
- * Returns the map's minimum allowable zoom level.
677
- *
678
- * @returns {number} minZoom
679
- * @example
680
- * var minZoom = map.getMinZoom();
681
- */
682
- getMinZoom() { return this.transform.minZoom; }
683
-
684
- /**
685
- * Sets or clears the map's maximum zoom level.
686
- * If the map's current zoom level is higher than the new maximum,
687
- * the map will zoom to the new maximum.
688
- *
689
- * @param {number | null | undefined} maxZoom The maximum zoom level to set.
690
- * If `null` or `undefined` is provided, the function removes the current maximum zoom (sets it to 22).
691
- * @returns {Map} `this`
692
- * @example
693
- * map.setMaxZoom(18.75);
694
- */
695
- setMaxZoom(maxZoom?: ?number) {
696
-
697
- maxZoom = maxZoom === null || maxZoom === undefined ? defaultMaxZoom : maxZoom;
698
-
699
- if (maxZoom >= this.transform.minZoom) {
700
- this.transform.maxZoom = maxZoom;
701
- this._update();
702
-
703
- if (this.getZoom() > maxZoom) this.setZoom(maxZoom);
704
-
705
- return this;
706
-
707
- } else throw new Error(`maxZoom must be greater than the current minZoom`);
708
- }
709
-
710
- /**
711
- * Returns the map's maximum allowable zoom level.
712
- *
713
- * @returns {number} maxZoom
714
- * @example
715
- * var maxZoom = map.getMaxZoom();
716
- */
717
- getMaxZoom() { return this.transform.maxZoom; }
718
-
719
- /**
720
- * Sets or clears the map's minimum pitch.
721
- * If the map's current pitch is lower than the new minimum,
722
- * the map will pitch to the new minimum.
723
- *
724
- * @param {number | null | undefined} minPitch The minimum pitch to set (0-60).
725
- * If `null` or `undefined` is provided, the function removes the current minimum pitch (i.e. sets it to 0).
726
- * @returns {Map} `this`
727
- */
728
- setMinPitch(minPitch?: ?number) {
729
-
730
- minPitch = minPitch === null || minPitch === undefined ? defaultMinPitch : minPitch;
731
-
732
- if (minPitch < defaultMinPitch) {
733
- throw new Error(`minPitch must be greater than or equal to ${defaultMinPitch}`);
734
- }
735
-
736
- if (minPitch >= defaultMinPitch && minPitch <= this.transform.maxPitch) {
737
- this.transform.minPitch = minPitch;
738
- this._update();
739
-
740
- if (this.getPitch() < minPitch) this.setPitch(minPitch);
741
-
742
- return this;
743
-
744
- } else throw new Error(`minPitch must be between ${defaultMinPitch} and the current maxPitch, inclusive`);
745
- }
746
-
747
- /**
748
- * Returns the map's minimum allowable pitch.
749
- *
750
- * @returns {number} minPitch
751
- */
752
- getMinPitch() { return this.transform.minPitch; }
753
-
754
- /**
755
- * Sets or clears the map's maximum pitch.
756
- * If the map's current pitch is higher than the new maximum,
757
- * the map will pitch to the new maximum.
758
- *
759
- * @param {number | null | undefined} maxPitch The maximum pitch to set.
760
- * If `null` or `undefined` is provided, the function removes the current maximum pitch (sets it to 60).
761
- * @returns {Map} `this`
762
- */
763
- setMaxPitch(maxPitch?: ?number) {
764
-
765
- maxPitch = maxPitch === null || maxPitch === undefined ? defaultMaxPitch : maxPitch;
766
-
767
- if (maxPitch > defaultMaxPitch) {
768
- throw new Error(`maxPitch must be less than or equal to ${defaultMaxPitch}`);
769
- }
770
-
771
- if (maxPitch >= this.transform.minPitch) {
772
- this.transform.maxPitch = maxPitch;
773
- this._update();
774
-
775
- if (this.getPitch() > maxPitch) this.setPitch(maxPitch);
776
-
777
- return this;
778
-
779
- } else throw new Error(`maxPitch must be greater than the current minPitch`);
780
- }
781
-
782
- /**
783
- * Returns the map's maximum allowable pitch.
784
- *
785
- * @returns {number} maxPitch
786
- */
787
- getMaxPitch() { return this.transform.maxPitch; }
788
-
789
- /**
790
- * Returns the state of `renderWorldCopies`. If `true`, multiple copies of the world will be rendered side by side beyond -180 and 180 degrees longitude. If set to `false`:
791
- * - When the map is zoomed out far enough that a single representation of the world does not fill the map's entire
792
- * container, there will be blank space beyond 180 and -180 degrees longitude.
793
- * - Features that cross 180 and -180 degrees longitude will be cut in two (with one portion on the right edge of the
794
- * map and the other on the left edge of the map) at every zoom level.
795
- * @returns {boolean} renderWorldCopies
796
- * @example
797
- * var worldCopiesRendered = map.getRenderWorldCopies();
798
- * @see [Render world copies](https://docs.mapbox.com/mapbox-gl-js/example/render-world-copies/)
799
- */
800
- getRenderWorldCopies() { return this.transform.renderWorldCopies; }
801
-
802
- /**
803
- * Sets the state of `renderWorldCopies`.
804
- *
805
- * @param {boolean} renderWorldCopies If `true`, multiple copies of the world will be rendered side by side beyond -180 and 180 degrees longitude. If set to `false`:
806
- * - When the map is zoomed out far enough that a single representation of the world does not fill the map's entire
807
- * container, there will be blank space beyond 180 and -180 degrees longitude.
808
- * - Features that cross 180 and -180 degrees longitude will be cut in two (with one portion on the right edge of the
809
- * map and the other on the left edge of the map) at every zoom level.
810
- *
811
- * `undefined` is treated as `true`, `null` is treated as `false`.
812
- * @returns {Map} `this`
813
- * @example
814
- * map.setRenderWorldCopies(true);
815
- * @see [Render world copies](https://docs.mapbox.com/mapbox-gl-js/example/render-world-copies/)
816
- */
817
- setRenderWorldCopies(renderWorldCopies?: ?boolean) {
818
- this.transform.renderWorldCopies = renderWorldCopies;
819
- return this._update();
820
- }
821
-
822
- /**
823
- * Returns a {@link Point} representing pixel coordinates, relative to the map's `container`,
824
- * that correspond to the specified geographical location.
825
- *
826
- * @param {LngLatLike} lnglat The geographical location to project.
827
- * @returns {Point} The {@link Point} corresponding to `lnglat`, relative to the map's `container`.
828
- * @example
829
- * var coordinate = [-122.420679, 37.772537];
830
- * var point = map.project(coordinate);
831
- */
832
- project(lnglat: LngLatLike) {
833
- return this.transform.locationPoint(LngLat.convert(lnglat));
834
- }
835
-
836
- /**
837
- * Returns a {@link LngLat} representing geographical coordinates that correspond
838
- * to the specified pixel coordinates.
839
- *
840
- * @param {PointLike} point The pixel coordinates to unproject.
841
- * @returns {LngLat} The {@link LngLat} corresponding to `point`.
842
- * @example
843
- * map.on('click', function(e) {
844
- * // When the map is clicked, get the geographic coordinate.
845
- * var coordinate = map.unproject(e.point);
846
- * });
847
- */
848
- unproject(point: PointLike) {
849
- return this.transform.pointLocation(Point.convert(point));
850
- }
851
-
852
- /**
853
- * Returns true if the map is panning, zooming, rotating, or pitching due to a camera animation or user gesture.
854
- * @returns {boolean} True if the map is moving.
855
- * @example
856
- * var isMoving = map.isMoving();
857
- */
858
- isMoving(): boolean {
859
- return this._moving ||
860
- this.dragPan.isActive() ||
861
- this.dragRotate.isActive() ||
862
- this.scrollZoom.isActive();
863
- }
864
-
865
- /**
866
- * Returns true if the map is zooming due to a camera animation or user gesture.
867
- * @returns {boolean} True if the map is zooming.
868
- * @example
869
- * var isZooming = map.isZooming();
870
- */
871
- isZooming(): boolean {
872
- return this._zooming ||
873
- this.scrollZoom.isZooming();
874
- }
875
-
876
- /**
877
- * Returns true if the map is rotating due to a camera animation or user gesture.
878
- * @returns {boolean} True if the map is rotating.
879
- * @example
880
- * map.isRotating();
881
- */
882
- isRotating(): boolean {
883
- return this._rotating ||
884
- this.dragRotate.isActive();
885
- }
886
-
887
- _createDelegatedListener(type: MapEvent, layerId: any, listener: any) {
888
- if (type === 'mouseenter' || type === 'mouseover') {
889
- let mousein = false;
890
- const mousemove = (e) => {
891
- const features = this.getLayer(layerId) ? this.queryRenderedFeatures(e.point, {layers: [layerId]}) : [];
892
- if (!features.length) {
893
- mousein = false;
894
- } else if (!mousein) {
895
- mousein = true;
896
- listener.call(this, new MapMouseEvent(type, this, e.originalEvent, {features}));
897
- }
898
- };
899
- const mouseout = () => {
900
- mousein = false;
901
- };
902
- return {layer: layerId, listener, delegates: {mousemove, mouseout}};
903
- } else if (type === 'mouseleave' || type === 'mouseout') {
904
- let mousein = false;
905
- const mousemove = (e) => {
906
- const features = this.getLayer(layerId) ? this.queryRenderedFeatures(e.point, {layers: [layerId]}) : [];
907
- if (features.length) {
908
- mousein = true;
909
- } else if (mousein) {
910
- mousein = false;
911
- listener.call(this, new MapMouseEvent(type, this, e.originalEvent));
912
- }
913
- };
914
- const mouseout = (e) => {
915
- if (mousein) {
916
- mousein = false;
917
- listener.call(this, new MapMouseEvent(type, this, e.originalEvent));
918
- }
919
- };
920
- return {layer: layerId, listener, delegates: {mousemove, mouseout}};
921
- } else {
922
- const delegate = (e) => {
923
- const features = this.getLayer(layerId) ? this.queryRenderedFeatures(e.point, {layers: [layerId]}) : [];
924
- if (features.length) {
925
- // Here we need to mutate the original event, so that preventDefault works as expected.
926
- e.features = features;
927
- listener.call(this, e);
928
- delete e.features;
929
- }
930
- };
931
- return {layer: layerId, listener, delegates: {[type]: delegate}};
932
- }
933
- }
934
-
935
- /**
936
- * Adds a listener for events of a specified type.
937
- *
938
- * @method
939
- * @name on
940
- * @memberof Map
941
- * @instance
942
- * @param {string} type The event type to add a listen for.
943
- * @param {Function} listener The function to be called when the event is fired.
944
- * The listener function is called with the data object passed to `fire`,
945
- * extended with `target` and `type` properties.
946
- * @returns {Map} `this`
947
- */
948
-
949
- /**
950
- * Adds a listener for events of a specified type occurring on features in a specified style layer.
951
- *
952
- * @param {string} type The event type to listen for; one of `'mousedown'`, `'mouseup'`, `'click'`, `'dblclick'`,
953
- * `'mousemove'`, `'mouseenter'`, `'mouseleave'`, `'mouseover'`, `'mouseout'`, `'contextmenu'`, `'touchstart'`,
954
- * `'touchend'`, or `'touchcancel'`. `mouseenter` and `mouseover` events are triggered when the cursor enters
955
- * a visible portion of the specified layer from outside that layer or outside the map canvas. `mouseleave`
956
- * and `mouseout` events are triggered when the cursor leaves a visible portion of the specified layer, or leaves
957
- * the map canvas.
958
- * @param {string} layerId The ID of a style layer. Only events whose location is within a visible
959
- * feature in this layer will trigger the listener. The event will have a `features` property containing
960
- * an array of the matching features.
961
- * @param {Function} listener The function to be called when the event is fired.
962
- * @returns {Map} `this`
963
- */
964
- on(type: MapEvent, layerId: any, listener: any) {
965
- if (listener === undefined) {
966
- return super.on(type, layerId);
967
- }
968
-
969
- const delegatedListener = this._createDelegatedListener(type, layerId, listener);
970
-
971
- this._delegatedListeners = this._delegatedListeners || {};
972
- this._delegatedListeners[type] = this._delegatedListeners[type] || [];
973
- this._delegatedListeners[type].push(delegatedListener);
974
-
975
- for (const event in delegatedListener.delegates) {
976
- this.on((event: any), delegatedListener.delegates[event]);
977
- }
978
-
979
- return this;
980
- }
981
-
982
- /**
983
- * Adds a listener that will be called only once to a specified event type.
984
- *
985
- * @method
986
- * @name once
987
- * @memberof Map
988
- * @instance
989
- * @param {string} type The event type to add a listener for.
990
- * @param {Function} listener The function to be called when the event is fired.
991
- * The listener function is called with the data object passed to `fire`,
992
- * extended with `target` and `type` properties.
993
- * @returns {Map} `this`
994
- */
995
-
996
- /**
997
- * Adds a listener that will be called only once to a specified event type occurring on features in a specified style layer.
998
- *
999
- * @param {string} type The event type to listen for; one of `'mousedown'`, `'mouseup'`, `'click'`, `'dblclick'`,
1000
- * `'mousemove'`, `'mouseenter'`, `'mouseleave'`, `'mouseover'`, `'mouseout'`, `'contextmenu'`, `'touchstart'`,
1001
- * `'touchend'`, or `'touchcancel'`. `mouseenter` and `mouseover` events are triggered when the cursor enters
1002
- * a visible portion of the specified layer from outside that layer or outside the map canvas. `mouseleave`
1003
- * and `mouseout` events are triggered when the cursor leaves a visible portion of the specified layer, or leaves
1004
- * the map canvas.
1005
- * @param {string} layerId The ID of a style layer. Only events whose location is within a visible
1006
- * feature in this layer will trigger the listener. The event will have a `features` property containing
1007
- * an array of the matching features.
1008
- * @param {Function} listener The function to be called when the event is fired.
1009
- * @returns {Map} `this`
1010
- */
1011
-
1012
- once(type: MapEvent, layerId: any, listener: any) {
1013
-
1014
- if (listener === undefined) {
1015
- return super.once(type, layerId);
1016
- }
1017
-
1018
- const delegatedListener = this._createDelegatedListener(type, layerId, listener);
1019
-
1020
- for (const event in delegatedListener.delegates) {
1021
- this.once((event: any), delegatedListener.delegates[event]);
1022
- }
1023
-
1024
- return this;
1025
- }
1026
-
1027
- /**
1028
- * Removes an event listener previously added with `Map#on`.
1029
- *
1030
- * @method
1031
- * @name off
1032
- * @memberof Map
1033
- * @instance
1034
- * @param {string} type The event type previously used to install the listener.
1035
- * @param {Function} listener The function previously installed as a listener.
1036
- * @returns {Map} `this`
1037
- */
1038
-
1039
- /**
1040
- * Removes an event listener for layer-specific events previously added with `Map#on`.
1041
- *
1042
- * @param {string} type The event type previously used to install the listener.
1043
- * @param {string} layerId The layer ID previously used to install the listener.
1044
- * @param {Function} listener The function previously installed as a listener.
1045
- * @returns {Map} `this`
1046
- */
1047
- off(type: MapEvent, layerId: any, listener: any) {
1048
- if (listener === undefined) {
1049
- return super.off(type, layerId);
1050
- }
1051
-
1052
- const removeDelegatedListener = (delegatedListeners) => {
1053
- const listeners = delegatedListeners[type];
1054
- for (let i = 0; i < listeners.length; i++) {
1055
- const delegatedListener = listeners[i];
1056
- if (delegatedListener.layer === layerId && delegatedListener.listener === listener) {
1057
- for (const event in delegatedListener.delegates) {
1058
- this.off((event: any), delegatedListener.delegates[event]);
1059
- }
1060
- listeners.splice(i, 1);
1061
- return this;
1062
- }
1063
- }
1064
- };
1065
-
1066
- if (this._delegatedListeners && this._delegatedListeners[type]) {
1067
- removeDelegatedListener(this._delegatedListeners);
1068
- }
1069
-
1070
- return this;
1071
- }
1072
-
1073
- /**
1074
- * Returns an array of [GeoJSON](http://geojson.org/)
1075
- * [Feature objects](https://tools.ietf.org/html/rfc7946#section-3.2)
1076
- * representing visible features that satisfy the query parameters.
1077
- *
1078
- * @param {PointLike|Array<PointLike>} [geometry] - The geometry of the query region:
1079
- * either a single point or southwest and northeast points describing a bounding box.
1080
- * Omitting this parameter (i.e. calling {@link Map#queryRenderedFeatures} with zero arguments,
1081
- * or with only a `options` argument) is equivalent to passing a bounding box encompassing the entire
1082
- * map viewport.
1083
- * @param {Object} [options] Options object.
1084
- * @param {Array<string>} [options.layers] An array of [style layer IDs](https://docs.mapbox.com/mapbox-gl-js/style-spec/#layer-id) for the query to inspect.
1085
- * Only features within these layers will be returned. If this parameter is undefined, all layers will be checked.
1086
- * @param {Array} [options.filter] A [filter](https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/#filter)
1087
- * to limit query results.
1088
- * @param {boolean} [options.validate=true] Whether to check if the [options.filter] conforms to the Mapbox GL Style Specification. Disabling validation is a performance optimization that should only be used if you have previously validated the values you will be passing to this function.
1089
- *
1090
- * @returns {Array<Object>} An array of [GeoJSON](http://geojson.org/)
1091
- * [feature objects](https://tools.ietf.org/html/rfc7946#section-3.2).
1092
- *
1093
- * The `properties` value of each returned feature object contains the properties of its source feature. For GeoJSON sources, only
1094
- * string and numeric property values are supported (i.e. `null`, `Array`, and `Object` values are not supported).
1095
- *
1096
- * Each feature includes top-level `layer`, `source`, and `sourceLayer` properties. The `layer` property is an object
1097
- * representing the style layer to which the feature belongs. Layout and paint properties in this object contain values
1098
- * which are fully evaluated for the given zoom level and feature.
1099
- *
1100
- * Only features that are currently rendered are included. Some features will **not** be included, like:
1101
- *
1102
- * - Features from layers whose `visibility` property is `"none"`.
1103
- * - Features from layers whose zoom range excludes the current zoom level.
1104
- * - Symbol features that have been hidden due to text or icon collision.
1105
- *
1106
- * Features from all other layers are included, including features that may have no visible
1107
- * contribution to the rendered result; for example, because the layer's opacity or color alpha component is set to
1108
- * 0.
1109
- *
1110
- * The topmost rendered feature appears first in the returned array, and subsequent features are sorted by
1111
- * descending z-order. Features that are rendered multiple times (due to wrapping across the antimeridian at low
1112
- * zoom levels) are returned only once (though subject to the following caveat).
1113
- *
1114
- * Because features come from tiled vector data or GeoJSON data that is converted to tiles internally, feature
1115
- * geometries may be split or duplicated across tile boundaries and, as a result, features may appear multiple
1116
- * times in query results. For example, suppose there is a highway running through the bounding rectangle of a query.
1117
- * The results of the query will be those parts of the highway that lie within the map tiles covering the bounding
1118
- * rectangle, even if the highway extends into other tiles, and the portion of the highway within each map tile
1119
- * will be returned as a separate feature. Similarly, a point feature near a tile boundary may appear in multiple
1120
- * tiles due to tile buffering.
1121
- *
1122
- * @example
1123
- * // Find all features at a point
1124
- * var features = map.queryRenderedFeatures(
1125
- * [20, 35],
1126
- * { layers: ['my-layer-name'] }
1127
- * );
1128
- *
1129
- * @example
1130
- * // Find all features within a static bounding box
1131
- * var features = map.queryRenderedFeatures(
1132
- * [[10, 20], [30, 50]],
1133
- * { layers: ['my-layer-name'] }
1134
- * );
1135
- *
1136
- * @example
1137
- * // Find all features within a bounding box around a point
1138
- * var width = 10;
1139
- * var height = 20;
1140
- * var features = map.queryRenderedFeatures([
1141
- * [point.x - width / 2, point.y - height / 2],
1142
- * [point.x + width / 2, point.y + height / 2]
1143
- * ], { layers: ['my-layer-name'] });
1144
- *
1145
- * @example
1146
- * // Query all rendered features from a single layer
1147
- * var features = map.queryRenderedFeatures({ layers: ['my-layer-name'] });
1148
- * @see [Get features under the mouse pointer](https://www.mapbox.com/mapbox-gl-js/example/queryrenderedfeatures/)
1149
- * @see [Highlight features within a bounding box](https://www.mapbox.com/mapbox-gl-js/example/using-box-queryrenderedfeatures/)
1150
- * @see [Filter features within map view](https://www.mapbox.com/mapbox-gl-js/example/filter-features-within-map-view/)
1151
- */
1152
- queryRenderedFeatures(geometry?: PointLike | [PointLike, PointLike], options?: Object) {
1153
- // The first parameter can be omitted entirely, making this effectively an overloaded method
1154
- // with two signatures:
1155
- //
1156
- // queryRenderedFeatures(geometry: PointLike | [PointLike, PointLike], options?: Object)
1157
- // queryRenderedFeatures(options?: Object)
1158
- //
1159
- // There no way to express that in a way that's compatible with both flow and documentation.js.
1160
- // Related: https://github.com/facebook/flow/issues/1556
1161
-
1162
- if (!this.style) {
1163
- return [];
1164
- }
1165
-
1166
- if (options === undefined && geometry !== undefined && !(geometry instanceof Point) && !Array.isArray(geometry)) {
1167
- options = (geometry: Object);
1168
- geometry = undefined;
1169
- }
1170
-
1171
- options = options || {};
1172
- geometry = geometry || [[0, 0], [this.transform.width, this.transform.height]];
1173
-
1174
- let queryGeometry;
1175
- if (geometry instanceof Point || typeof geometry[0] === 'number') {
1176
- queryGeometry = [Point.convert(geometry)];
1177
- } else {
1178
- const tl = Point.convert(geometry[0]);
1179
- const br = Point.convert(geometry[1]);
1180
- queryGeometry = [tl, new Point(br.x, tl.y), br, new Point(tl.x, br.y), tl];
1181
- }
1182
-
1183
- return this.style.queryRenderedFeatures(queryGeometry, options, this.transform);
1184
- }
1185
-
1186
- /**
1187
- * Returns an array of [GeoJSON](http://geojson.org/)
1188
- * [Feature objects](https://tools.ietf.org/html/rfc7946#section-3.2)
1189
- * representing features within the specified vector tile or GeoJSON source that satisfy the query parameters.
1190
- *
1191
- * @param {string} sourceId The ID of the vector tile or GeoJSON source to query.
1192
- * @param {Object} [parameters] Options object.
1193
- * @param {string} [parameters.sourceLayer] The name of the [source layer](https://docs.mapbox.com/help/glossary/source-layer/)
1194
- * to query. *For vector tile sources, this parameter is required.* For GeoJSON sources, it is ignored.
1195
- * @param {Array} [parameters.filter] A [filter](https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/#filter)
1196
- * to limit query results.
1197
- * @param {boolean} [parameters.validate=true] Whether to check if the [parameters.filter] conforms to the Mapbox GL Style Specification. Disabling validation is a performance optimization that should only be used if you have previously validated the values you will be passing to this function.
1198
- *
1199
- * @returns {Array<Object>} An array of [GeoJSON](http://geojson.org/)
1200
- * [Feature objects](https://tools.ietf.org/html/rfc7946#section-3.2).
1201
- *
1202
- * In contrast to {@link Map#queryRenderedFeatures}, this function returns all features matching the query parameters,
1203
- * whether or not they are rendered by the current style (i.e. visible). The domain of the query includes all currently-loaded
1204
- * vector tiles and GeoJSON source tiles: this function does not check tiles outside the currently
1205
- * visible viewport.
1206
- *
1207
- * Because features come from tiled vector data or GeoJSON data that is converted to tiles internally, feature
1208
- * geometries may be split or duplicated across tile boundaries and, as a result, features may appear multiple
1209
- * times in query results. For example, suppose there is a highway running through the bounding rectangle of a query.
1210
- * The results of the query will be those parts of the highway that lie within the map tiles covering the bounding
1211
- * rectangle, even if the highway extends into other tiles, and the portion of the highway within each map tile
1212
- * will be returned as a separate feature. Similarly, a point feature near a tile boundary may appear in multiple
1213
- * tiles due to tile buffering.
1214
- *
1215
- * @example
1216
- * // Find all features in one source layer in a vector source
1217
- * var features = map.querySourceFeatures('your-source-id', {
1218
- * sourceLayer: 'your-source-layer'
1219
- * });
1220
- *
1221
- * @see [Highlight features containing similar data](https://www.mapbox.com/mapbox-gl-js/example/query-similar-features/)
1222
- */
1223
- querySourceFeatures(sourceId: string, parameters: ?{sourceLayer: ?string, filter: ?Array<any>, validate?: boolean}) {
1224
- return this.style.querySourceFeatures(sourceId, parameters);
1225
- }
1226
-
1227
- /**
1228
- * Updates the map's Mapbox style object with a new value.
1229
- *
1230
- * If a style is already set when this is used and options.diff is set to true, the map renderer will attempt to compare the given style
1231
- * against the map's current state and perform only the changes necessary to make the map style match the desired state. Changes in sprites
1232
- * (images used for icons and patterns) and glyphs (fonts for label text) **cannot** be diffed. If the sprites or fonts used in the current
1233
- * style and the given style are different in any way, the map renderer will force a full update, removing the current style and building
1234
- * the given one from scratch.
1235
- *
1236
- *
1237
- * @param style A JSON object conforming to the schema described in the
1238
- * [Mapbox Style Specification](https://mapbox.com/mapbox-gl-style-spec/), or a URL to such JSON.
1239
- * @param {Object} [options] Options object.
1240
- * @param {boolean} [options.diff=true] If false, force a 'full' update, removing the current style
1241
- * and building the given one instead of attempting a diff-based update.
1242
- * @param {string} [options.localIdeographFontFamily='sans-serif'] Defines a CSS
1243
- * font-family for locally overriding generation of glyphs in the 'CJK Unified Ideographs', 'Hiragana', 'Katakana' and 'Hangul Syllables' ranges.
1244
- * In these ranges, font settings from the map's style will be ignored, except for font-weight keywords (light/regular/medium/bold).
1245
- * Set to `false`, to enable font settings from the map's style for these glyph ranges.
1246
- * Forces a full update.
1247
- * @returns {Map} `this`
1248
- *
1249
- * @example
1250
- * map.setStyle("mapbox://styles/mapbox/streets-v11");
1251
- *
1252
- * @see [Change a map's style](https://www.mapbox.com/mapbox-gl-js/example/setstyle/)
1253
- */
1254
- setStyle(style: StyleSpecification | string | null, options?: {diff?: boolean} & StyleOptions) {
1255
- options = extend({}, {localIdeographFontFamily: this._localIdeographFontFamily}, options);
1256
-
1257
- if ((options.diff !== false && options.localIdeographFontFamily === this._localIdeographFontFamily) && this.style && style) {
1258
- this._diffStyle(style, options);
1259
- return this;
1260
- } else {
1261
- this._localIdeographFontFamily = options.localIdeographFontFamily;
1262
- return this._updateStyle(style, options);
1263
- }
1264
- }
1265
-
1266
- _getUIString(key: string) {
1267
- const str = this._locale[key];
1268
- if (str == null) {
1269
- throw new Error(`Missing UI string '${key}'`);
1270
- }
1271
-
1272
- return str;
1273
- }
1274
-
1275
- _updateStyle(style: StyleSpecification | string | null, options?: {diff?: boolean} & StyleOptions) {
1276
- if (this.style) {
1277
- this.style.setEventedParent(null);
1278
- this.style._remove();
1279
- }
1280
-
1281
- if (!style) {
1282
- delete this.style;
1283
- return this;
1284
- } else {
1285
- this.style = new Style(this, options || {});
1286
- }
1287
-
1288
- this.style.setEventedParent(this, {style: this.style});
1289
-
1290
- if (typeof style === 'string') {
1291
- this.style.loadURL(style);
1292
- } else {
1293
- this.style.loadJSON(style);
1294
- }
1295
-
1296
- return this;
1297
- }
1298
-
1299
- _lazyInitEmptyStyle() {
1300
- if (!this.style) {
1301
- this.style = new Style(this, {});
1302
- this.style.setEventedParent(this, {style: this.style});
1303
- this.style.loadEmpty();
1304
- }
1305
- }
1306
-
1307
- _diffStyle(style: StyleSpecification | string, options?: {diff?: boolean} & StyleOptions) {
1308
- if (typeof style === 'string') {
1309
- const url = this._requestManager.normalizeStyleURL(style);
1310
- const request = this._requestManager.transformRequest(url, ResourceType.Style);
1311
- getJSON(request, (error: ?Error, json: ?Object) => {
1312
- if (error) {
1313
- this.fire(new ErrorEvent(error));
1314
- } else if (json) {
1315
- this._updateDiff(json, options);
1316
- }
1317
- });
1318
- } else if (typeof style === 'object') {
1319
- this._updateDiff(style, options);
1320
- }
1321
- }
1322
-
1323
- _updateDiff(style: StyleSpecification, options?: {diff?: boolean} & StyleOptions) {
1324
- try {
1325
- if (this.style.setState(style)) {
1326
- this._update(true);
1327
- }
1328
- } catch (e) {
1329
- warnOnce(
1330
- `Unable to perform style diff: ${e.message || e.error || e}. Rebuilding the style from scratch.`
1331
- );
1332
- this._updateStyle(style, options);
1333
- }
1334
- }
1335
-
1336
- /**
1337
- * Returns the map's Mapbox style object, which can be used to recreate the map's style.
1338
- *
1339
- * @returns {Object} The map's style object.
1340
- *
1341
- * @example
1342
- * var styleJson = map.getStyle();
1343
- *
1344
- */
1345
- getStyle() {
1346
- if (this.style) {
1347
- return this.style.serialize();
1348
- }
1349
- }
1350
-
1351
- /**
1352
- * Returns a Boolean indicating whether the map's style is fully loaded.
1353
- *
1354
- * @returns {boolean} A Boolean indicating whether the style is fully loaded.
1355
- *
1356
- * @example
1357
- * var styleLoadStatus = map.isStyleLoaded();
1358
- */
1359
- isStyleLoaded() {
1360
- if (!this.style) return warnOnce('There is no style added to the map.');
1361
- return this.style.loaded();
1362
- }
1363
-
1364
- /**
1365
- * Adds a source to the map's style.
1366
- *
1367
- * @param {string} id The ID of the source to add. Must not conflict with existing sources.
1368
- * @param {Object} source The source object, conforming to the
1369
- * Mapbox Style Specification's [source definition](https://www.mapbox.com/mapbox-gl-style-spec/#sources) or
1370
- * {@link CanvasSourceOptions}.
1371
- * @fires source.add
1372
- * @returns {Map} `this`
1373
- * @example
1374
- * map.addSource('my-data', {
1375
- * type: 'vector',
1376
- * url: 'mapbox://myusername.tilesetid'
1377
- * });
1378
- * @example
1379
- * map.addSource('my-data', {
1380
- * "type": "geojson",
1381
- * "data": {
1382
- * "type": "Feature",
1383
- * "geometry": {
1384
- * "type": "Point",
1385
- * "coordinates": [-77.0323, 38.9131]
1386
- * },
1387
- * "properties": {
1388
- * "title": "Mapbox DC",
1389
- * "marker-symbol": "monument"
1390
- * }
1391
- * }
1392
- * });
1393
- * @see Vector source: [Show and hide layers](https://docs.mapbox.com/mapbox-gl-js/example/toggle-layers/)
1394
- * @see GeoJSON source: [Add live realtime data](https://docs.mapbox.com/mapbox-gl-js/example/live-geojson/)
1395
- * @see Raster DEM source: [Add hillshading](https://docs.mapbox.com/mapbox-gl-js/example/hillshade/)
1396
- */
1397
- addSource(id: string, source: SourceSpecification) {
1398
- this._lazyInitEmptyStyle();
1399
- this.style.addSource(id, source);
1400
- return this._update(true);
1401
- }
1402
-
1403
- /**
1404
- * Returns a Boolean indicating whether the source is loaded.
1405
- *
1406
- * @param {string} id The ID of the source to be checked.
1407
- * @returns {boolean} A Boolean indicating whether the source is loaded.
1408
- * @example
1409
- * var sourceLoaded = map.isSourceLoaded('bathymetry-data');
1410
- */
1411
- isSourceLoaded(id: string) {
1412
- const source = this.style && this.style.sourceCaches[id];
1413
- if (source === undefined) {
1414
- this.fire(new ErrorEvent(new Error(`There is no source with ID '${id}'`)));
1415
- return;
1416
- }
1417
- return source.loaded();
1418
- }
1419
-
1420
- /**
1421
- * Returns a Boolean indicating whether all tiles in the viewport from all sources on
1422
- * the style are loaded.
1423
- *
1424
- * @returns {boolean} A Boolean indicating whether all tiles are loaded.
1425
- * @example
1426
- * var tilesLoaded = map.areTilesLoaded();
1427
- */
1428
-
1429
- areTilesLoaded() {
1430
- const sources = this.style && this.style.sourceCaches;
1431
- for (const id in sources) {
1432
- const source = sources[id];
1433
- const tiles = source._tiles;
1434
- for (const t in tiles) {
1435
- const tile = tiles[t];
1436
- if (!(tile.state === 'loaded' || tile.state === 'errored')) return false;
1437
- }
1438
- }
1439
- return true;
1440
- }
1441
-
1442
- /**
1443
- * Adds a [custom source type](#Custom Sources), making it available for use with
1444
- * {@link Map#addSource}.
1445
- * @private
1446
- * @param {string} name The name of the source type; source definition objects use this name in the `{type: ...}` field.
1447
- * @param {Function} SourceType A {@link Source} constructor.
1448
- * @param {Function} callback Called when the source type is ready or with an error argument if there is an error.
1449
- */
1450
- addSourceType(name: string, SourceType: any, callback: Function) {
1451
- this._lazyInitEmptyStyle();
1452
- return this.style.addSourceType(name, SourceType, callback);
1453
- }
1454
-
1455
- /**
1456
- * Removes a source from the map's style.
1457
- *
1458
- * @param {string} id The ID of the source to remove.
1459
- * @returns {Map} `this`
1460
- * @example
1461
- * map.removeSource('bathymetry-data');
1462
- */
1463
- removeSource(id: string) {
1464
- this.style.removeSource(id);
1465
- return this._update(true);
1466
- }
1467
-
1468
- /**
1469
- * Returns the source with the specified ID in the map's style.
1470
- *
1471
- * @param {string} id The ID of the source to get.
1472
- * @returns {?Object} The style source with the specified ID, or `undefined`
1473
- * if the ID corresponds to no existing sources.
1474
- * @example
1475
- * var sourceObject = map.getSource('points');
1476
- * @see [Create a draggable point](https://www.mapbox.com/mapbox-gl-js/example/drag-a-point/)
1477
- * @see [Animate a point](https://www.mapbox.com/mapbox-gl-js/example/animate-point-along-line/)
1478
- * @see [Add live realtime data](https://www.mapbox.com/mapbox-gl-js/example/live-geojson/)
1479
- */
1480
- getSource(id: string) {
1481
- return this.style.getSource(id);
1482
- }
1483
-
1484
- // eslint-disable-next-line jsdoc/require-returns
1485
- /**
1486
- * Add an image to the style. This image can be displayed on the map like any other icon in the style's
1487
- * [sprite](https://docs.mapbox.com/help/glossary/sprite/) using the image's ID with
1488
- * [`icon-image`](https://docs.mapbox.com/mapbox-gl-js/style-spec/#layout-symbol-icon-image),
1489
- * [`background-pattern`](https://docs.mapbox.com/mapbox-gl-js/style-spec/#paint-background-background-pattern),
1490
- * [`fill-pattern`](https://docs.mapbox.com/mapbox-gl-js/style-spec/#paint-fill-fill-pattern),
1491
- * or [`line-pattern`](https://docs.mapbox.com/mapbox-gl-js/style-spec/#paint-line-line-pattern).
1492
- * A {@link Map#error} event will be fired if there is not enough space in the sprite to add this image.
1493
- *
1494
- * @param id The ID of the image.
1495
- * @param image The image as an `HTMLImageElement`, `ImageData`, `ImageBitmap` or object with `width`, `height`, and `data`
1496
- * properties with the same format as `ImageData`.
1497
- * @param options Options object.
1498
- * @param options.pixelRatio The ratio of pixels in the image to physical pixels on the screen
1499
- * @param options.sdf Whether the image should be interpreted as an SDF image
1500
- * @param options.content `[x1, y1, x2, y2]` If `icon-text-fit` is used in a layer with this image, this option defines the part of the image that can be covered by the content in `text-field`.
1501
- * @param options.stretchX `[[x1, x2], ...]` If `icon-text-fit` is used in a layer with this image, this option defines the part(s) of the image that can be stretched horizontally.
1502
- * @param options.stretchY `[[y1, y2], ...]` If `icon-text-fit` is used in a layer with this image, this option defines the part(s) of the image that can be stretched vertically.
1503
- *
1504
- * @example
1505
- * // If the style's sprite does not already contain an image with ID 'cat',
1506
- * // add the image 'cat-icon.png' to the style's sprite with the ID 'cat'.
1507
- * map.loadImage('https://upload.wikimedia.org/wikipedia/commons/thumb/6/60/Cat_silhouette.svg/400px-Cat_silhouette.svg.png', function(error, image) {
1508
- * if (error) throw error;
1509
- * if (!map.hasImage('cat')) map.addImage('cat', image);
1510
- * });
1511
- *
1512
- *
1513
- * // Add a stretchable image that can be used with `icon-text-fit`
1514
- * // In this example, the image is 600px wide by 400px high.
1515
- * map.loadImage('https://upload.wikimedia.org/wikipedia/commons/8/89/Black_and_White_Boxed_%28bordered%29.png', function(error, image) {
1516
- * if (error) throw error;
1517
- * if (!map.hasImage('border-image')) {
1518
- * map.addImage('border-image', image, {
1519
- * content: [16, 16, 300, 384], // place text over left half of image, avoiding the 16px border
1520
- * stretchX: [[16, 584]], // stretch everything horizontally except the 16px border
1521
- * stretchY: [[16, 384]], // stretch everything vertically except the 16px border
1522
- * });
1523
- * }
1524
- * });
1525
- *
1526
- *
1527
- * @see Use `HTMLImageElement`: [Add an icon to the map](https://www.mapbox.com/mapbox-gl-js/example/add-image/)
1528
- * @see Use `ImageData`: [Add a generated icon to the map](https://www.mapbox.com/mapbox-gl-js/example/add-image-generated/)
1529
- */
1530
- addImage(id: string,
1531
- image: HTMLImageElement | ImageBitmap | ImageData | {width: number, height: number, data: Uint8Array | Uint8ClampedArray} | StyleImageInterface,
1532
- {pixelRatio = 1, sdf = false, stretchX, stretchY, content}: $Shape<StyleImageMetadata> = {}) {
1533
- this._lazyInitEmptyStyle();
1534
- const version = 0;
1535
-
1536
- if (image instanceof HTMLImageElement || (ImageBitmap && image instanceof ImageBitmap)) {
1537
- const {width, height, data} = browser.getImageData(image);
1538
- this.style.addImage(id, {data: new RGBAImage({width, height}, data), pixelRatio, stretchX, stretchY, content, sdf, version});
1539
- } else if (image.width === undefined || image.height === undefined) {
1540
- return this.fire(new ErrorEvent(new Error(
1541
- 'Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, ' +
1542
- 'or object with `width`, `height`, and `data` properties with the same format as `ImageData`')));
1543
- } else {
1544
- const {width, height, data} = image;
1545
- const userImage = ((image: any): StyleImageInterface);
1546
-
1547
- this.style.addImage(id, {
1548
- data: new RGBAImage({width, height}, new Uint8Array(data)),
1549
- pixelRatio,
1550
- stretchX,
1551
- stretchY,
1552
- content,
1553
- sdf,
1554
- version,
1555
- userImage
1556
- });
1557
-
1558
- if (userImage.onAdd) {
1559
- userImage.onAdd(this, id);
1560
- }
1561
- }
1562
- }
1563
-
1564
- // eslint-disable-next-line jsdoc/require-returns
1565
- /**
1566
- * Update an existing image in a style. This image can be displayed on the map like any other icon in the style's
1567
- * [sprite](https://docs.mapbox.com/help/glossary/sprite/) using the image's ID with
1568
- * [`icon-image`](https://docs.mapbox.com/mapbox-gl-js/style-spec/#layout-symbol-icon-image),
1569
- * [`background-pattern`](https://docs.mapbox.com/mapbox-gl-js/style-spec/#paint-background-background-pattern),
1570
- * [`fill-pattern`](https://docs.mapbox.com/mapbox-gl-js/style-spec/#paint-fill-fill-pattern),
1571
- * or [`line-pattern`](https://docs.mapbox.com/mapbox-gl-js/style-spec/#paint-line-line-pattern).
1572
- *
1573
- * @param id The ID of the image.
1574
- * @param image The image as an `HTMLImageElement`, `ImageData`, `ImageBitmap` or object with `width`, `height`, and `data`
1575
- * properties with the same format as `ImageData`.
1576
- *
1577
- * @example
1578
- * // If an image with the ID 'cat' already exists in the style's sprite,
1579
- * // replace that image with a new image, 'other-cat-icon.png'.
1580
- * if (map.hasImage('cat')) map.updateImage('cat', './other-cat-icon.png');
1581
- */
1582
- updateImage(id: string,
1583
- image: HTMLImageElement | ImageBitmap | ImageData | {width: number, height: number, data: Uint8Array | Uint8ClampedArray} | StyleImageInterface) {
1584
-
1585
- const existingImage = this.style.getImage(id);
1586
- if (!existingImage) {
1587
- return this.fire(new ErrorEvent(new Error(
1588
- 'The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.')));
1589
- }
1590
- const imageData = (image instanceof HTMLImageElement || (ImageBitmap && image instanceof ImageBitmap)) ? browser.getImageData(image) : image;
1591
- const {width, height, data} = imageData;
1592
-
1593
- if (width === undefined || height === undefined) {
1594
- return this.fire(new ErrorEvent(new Error(
1595
- 'Invalid arguments to map.updateImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, ' +
1596
- 'or object with `width`, `height`, and `data` properties with the same format as `ImageData`')));
1597
- }
1598
-
1599
- if (width !== existingImage.data.width || height !== existingImage.data.height) {
1600
- return this.fire(new ErrorEvent(new Error(
1601
- 'The width and height of the updated image must be that same as the previous version of the image')));
1602
- }
1603
-
1604
- const copy = !(image instanceof HTMLImageElement || (ImageBitmap && image instanceof ImageBitmap));
1605
- existingImage.data.replace(data, copy);
1606
-
1607
- this.style.updateImage(id, existingImage);
1608
- }
1609
-
1610
- /**
1611
- * Check whether or not an image with a specific ID exists in the style. This checks both images
1612
- * in the style's original [sprite](https://docs.mapbox.com/help/glossary/sprite/) and any images
1613
- * that have been added at runtime using {@link Map#addImage}.
1614
- *
1615
- * @param id The ID of the image.
1616
- *
1617
- * @returns {boolean} A Boolean indicating whether the image exists.
1618
- * @example
1619
- * // Check if an image with the ID 'cat' exists in
1620
- * // the style's sprite.
1621
- * var catIconExists = map.hasImage('cat');
1622
- */
1623
- hasImage(id: string): boolean {
1624
- if (!id) {
1625
- this.fire(new ErrorEvent(new Error('Missing required image id')));
1626
- return false;
1627
- }
1628
-
1629
- return !!this.style.getImage(id);
1630
- }
1631
-
1632
- /**
1633
- * Remove an image from a style. This can be an image from the style's original
1634
- * [sprite](https://docs.mapbox.com/help/glossary/sprite/) or any images
1635
- * that have been added at runtime using {@link Map#addImage}.
1636
- *
1637
- * @param id The ID of the image.
1638
- *
1639
- * @example
1640
- * // If an image with the ID 'cat' exists in
1641
- * // the style's sprite, remove it.
1642
- * if (map.hasImage('cat')) map.removeImage('cat');
1643
- */
1644
- removeImage(id: string) {
1645
- this.style.removeImage(id);
1646
- }
1647
-
1648
- /**
1649
- * Load an image from an external URL to be used with {@link Map#addImage}. External
1650
- * domains must support [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS).
1651
- *
1652
- * @param {string} url The URL of the image file. Image file must be in png, webp, or jpg format.
1653
- * @param {Function} callback Expecting `callback(error, data)`. Called when the image has loaded or with an error argument if there is an error.
1654
- *
1655
- * @example
1656
- * // Load an image from an external URL.
1657
- * map.loadImage('http://placekitten.com/50/50', function(error, image) {
1658
- * if (error) throw error;
1659
- * // Add the loaded image to the style's sprite with the ID 'kitten'.
1660
- * map.addImage('kitten', image);
1661
- * });
1662
- *
1663
- * @see [Add an icon to the map](https://www.mapbox.com/mapbox-gl-js/example/add-image/)
1664
- */
1665
- loadImage(url: string, callback: Function) {
1666
- getImage(this._requestManager.transformRequest(url, ResourceType.Image), callback);
1667
- }
1668
-
1669
- /**
1670
- * Returns an Array of strings containing the IDs of all images currently available in the map.
1671
- * This includes both images from the style's original [sprite](https://docs.mapbox.com/help/glossary/sprite/)
1672
- * and any images that have been added at runtime using {@link Map#addImage}.
1673
- *
1674
- * @returns {Array<string>} An Array of strings containing the names of all sprites/images currently available in the map.
1675
- *
1676
- * @example
1677
- * var allImages = map.listImages();
1678
- *
1679
- */
1680
- listImages() {
1681
- return this.style.listImages();
1682
- }
1683
-
1684
- /**
1685
- * Adds a [Mapbox style layer](https://docs.mapbox.com/mapbox-gl-js/style-spec/#layers)
1686
- * to the map's style.
1687
- *
1688
- * A layer defines how data from a specified source will be styled. Read more about layer types
1689
- * and available paint and layout properties in the [Mapbox Style Specification](https://docs.mapbox.com/mapbox-gl-js/style-spec/#layers).
1690
- *
1691
- * @param {Object | CustomLayerInterface} layer The style layer to add, conforming to the Mapbox Style Specification's
1692
- * [layer definition](https://docs.mapbox.com/mapbox-gl-js/style-spec/#layers).
1693
- * @param {string} [beforeId] The ID of an existing layer to insert the new layer before.
1694
- * If this argument is omitted, the layer will be appended to the end of the layers array.
1695
- *
1696
- * @returns {Map} `this`
1697
- *
1698
- * @example
1699
- * // Add a circle layer with a vector source.
1700
- * map.addLayer({
1701
- * id: 'points-of-interest',
1702
- * source: {
1703
- * type: 'vector',
1704
- * url: 'mapbox://mapbox.mapbox-streets-v8'
1705
- * },
1706
- * 'source-layer': 'poi_label',
1707
- * type: 'circle',
1708
- * paint: {
1709
- * // Mapbox Style Specification paint properties
1710
- * },
1711
- * layout: {
1712
- * // Mapbox Style Specification layout properties
1713
- * }
1714
- * });
1715
- *
1716
- * @see [Create and style clusters](https://www.mapbox.com/mapbox-gl-js/example/cluster/)
1717
- * @see [Add a vector tile source](https://www.mapbox.com/mapbox-gl-js/example/vector-source/)
1718
- * @see [Add a WMS source](https://www.mapbox.com/mapbox-gl-js/example/wms/)
1719
- */
1720
- addLayerBak(layer: LayerSpecification | CustomLayerInterface, beforeId?: string) {
1721
- this._lazyInitEmptyStyle();
1722
- this.style.addLayer(layer, beforeId);
1723
- return this._update(true);
1724
- }
1725
-
1726
- _addLayer(layer, map) {
1727
- layer.onAdd && layer.onAdd(map);
1728
- }
1729
-
1730
- /**
1731
- * @description 移除事件。
1732
- */
1733
- _removeLayer(layer) {
1734
- layer.removeFromMap && layer.removeFromMap();
1735
- }
1736
-
1737
- /**
1738
- * @description 设置图层可见性,设置图层的隐藏,显示,重绘的相应的可见标记。
1739
- * @param {boolean} [visibility] - 是否显示图层(当前地图的 resolution 在最大最小 resolution 之间)。
1740
- */
1741
- _setVisibility(layer, visibility) {
1742
- layer.setVisibility && layer.setVisibility(visibility);
1743
- }
1744
-
1745
- /**
1746
- * @description 将图层移动到某个图层之前。
1747
- * @param {string} layerID -待插入的图层 ID。
1748
- * @param {boolean} [beforeLayerID] - 是否将本图层插入到图层 id 为 layerID 的图层之前(如果为 false 则将本图层插入到图层 id 为 layerID 的图层之后)。
1749
- */
1750
- _moveLayer(layerID, beforeLayerID) {
1751
- var layer = document.getElementById(layerID);
1752
- // var beforeLayer;
1753
- if (beforeLayerID) {
1754
- var beforeLayer = document.getElementById(beforeLayerID);
1755
- if (!beforeLayer) {
1756
- window.mapboxgl.Evented.prototype.fire("error", {
1757
- error: new Error(`Layer with id "${beforeLayerID}" does not exist on this document.`)
1758
- });
1759
- }
1760
- }
1761
- if (layer && beforeLayer) {
1762
- beforeLayer.parentNode.insertBefore(layer, beforeLayer);
1763
- } else {
1764
- //当没有传入beforeLayerID ,则默认将图层移动到最上面
1765
- layer.parentNode.appendChild(layer);
1766
- }
1767
- }
1768
-
1769
- addLayer(layer, before) {
1770
- if (layer.source || layer.type === 'custom' || layer.type === "background") {
1771
- this.addLayerBak(layer, before);
1772
- return this;
1773
- }
1774
- if (this.overlayLayersManager[layer.id] || this.style._layers[layer.id]) {
1775
- this.fire('error', {
1776
- error: new Error('A layer with this id already exists.')
1777
- });
1778
- return;
1779
- }
1780
- this._addLayer(layer, this);
1781
- this.overlayLayersManager[layer.id] = layer;
1782
- return this;
1783
- };
1784
-
1785
- /**
1786
- * Moves a layer to a different z-position.
1787
- *
1788
- * @param {string} id The ID of the layer to move.
1789
- * @param {string} [beforeId] The ID of an existing layer to insert the new layer before.
1790
- * If this argument is omitted, the layer will be appended to the end of the layers array.
1791
- * @returns {Map} `this`
1792
- *
1793
- * @example
1794
- * // Move a layer with ID 'label' before the layer with ID 'waterways'.
1795
- * map.moveLayer('label', 'waterways');
1796
- */
1797
- moveLayer(id: string, beforeId?: string) {
1798
- if (this.overlayLayersManager[id]) {
1799
- this._moveLayer(id, beforeId);
1800
- return this;
1801
- }
1802
- if (this.style._layers[id]) {
1803
- this.style.moveLayer(id, beforeId);
1804
- this._update(true);
1805
- return this;
1806
- }
1807
- }
1808
-
1809
- // eslint-disable-next-line jsdoc/require-returns
1810
- /**
1811
- * Removes the layer with the given ID from the map's style.
1812
- *
1813
- * If no such layer exists, an `error` event is fired.
1814
- *
1815
- * @param {string} id id of the layer to remove
1816
- * @fires error
1817
- *
1818
- * @example
1819
- * // If a layer with ID 'state-data' exists, remove it.
1820
- * if (map.getLayer('state-data')) map.removeLayer('state-data');
1821
- */
1822
- removeLayer(id: string) {
1823
- if (this.overlayLayersManager[id]) {
1824
- this._removeLayer(this.overlayLayersManager[id]);
1825
- delete this.overlayLayersManager[id];
1826
- return this;
1827
- }
1828
- this.style.removeLayer(id);
1829
- this._update(true);
1830
- return this;
1831
- }
1832
-
1833
- /**
1834
- * Returns the layer with the specified ID in the map's style.
1835
- *
1836
- * @param {string} id The ID of the layer to get.
1837
- * @returns {?Object} The layer with the specified ID, or `undefined`
1838
- * if the ID corresponds to no existing layers.
1839
- *
1840
- * @example
1841
- * var stateDataLayer = map.getLayer('state-data');
1842
- *
1843
- * @see [Filter symbols by toggling a list](https://www.mapbox.com/mapbox-gl-js/example/filter-markers/)
1844
- * @see [Filter symbols by text input](https://www.mapbox.com/mapbox-gl-js/example/filter-markers-by-input/)
1845
- */
1846
- getLayer(id: string) {
1847
- if (this.overlayLayersManager[id]) {
1848
- return this.overlayLayersManager[id];
1849
- }
1850
- return this.style.getLayer(id);
1851
- }
1852
-
1853
- /**
1854
- * Sets the zoom extent for the specified style layer. The zoom extent includes the
1855
- * [minimum zoom level](https://docs.mapbox.com/mapbox-gl-js/style-spec/#layer-minzoom)
1856
- * and [maximum zoom level](https://docs.mapbox.com/mapbox-gl-js/style-spec/#layer-maxzoom))
1857
- * at which the layer will be rendered.
1858
- *
1859
- * Note: For style layers using vector sources, style layers cannot be rendered at zoom levels lower than the
1860
- * minimum zoom level of the _source layer_ because the data does not exist at those zoom levels. If the minimum
1861
- * zoom level of the source layer is higher than the minimum zoom level defined in the style layer, the style
1862
- * layer will not be rendered at all zoom levels in the zoom range.
1863
- *
1864
- * @param {string} layerId The ID of the layer to which the zoom extent will be applied.
1865
- * @param {number} minzoom The minimum zoom to set (0-24).
1866
- * @param {number} maxzoom The maximum zoom to set (0-24).
1867
- * @returns {Map} `this`
1868
- *
1869
- * @example
1870
- * map.setLayerZoomRange('my-layer', 2, 5);
1871
- *
1872
- */
1873
- setLayerZoomRange(layerId: string, minzoom: number, maxzoom: number) {
1874
- this.style.setLayerZoomRange(layerId, minzoom, maxzoom);
1875
- return this._update(true);
1876
- }
1877
-
1878
- /**
1879
- * Sets the filter for the specified style layer.
1880
- *
1881
- * @param {string} layerId The ID of the layer to which the filter will be applied.
1882
- * @param {Array | null | undefined} filter The filter, conforming to the Mapbox Style Specification's
1883
- * [filter definition](https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/#filter). If `null` or `undefined` is provided, the function removes any existing filter from the layer.
1884
- * @param {Object} [options] Options object.
1885
- * @param {boolean} [options.validate=true] Whether to check if the filter conforms to the Mapbox GL Style Specification. Disabling validation is a performance optimization that should only be used if you have previously validated the values you will be passing to this function.
1886
- *
1887
- * @returns {Map} `this`
1888
- * @example
1889
- * map.setFilter('my-layer', ['==', 'name', 'USA']);
1890
- *
1891
- * @see [Filter features within map view](https://www.mapbox.com/mapbox-gl-js/example/filter-features-within-map-view/)
1892
- * @see [Highlight features containing similar data](https://www.mapbox.com/mapbox-gl-js/example/query-similar-features/)
1893
- * @see [Create a timeline animation](https://www.mapbox.com/mapbox-gl-js/example/timeline-animation/)
1894
- */
1895
- setFilter(layerId: string, filter: ?FilterSpecification, options: StyleSetterOptions = {}) {
1896
- this.style.setFilter(layerId, filter, options);
1897
- return this._update(true);
1898
- }
1899
-
1900
- /**
1901
- * Returns the filter applied to the specified style layer.
1902
- *
1903
- * @param {string} layerId The ID of the style layer whose filter to get.
1904
- * @returns {Array} The layer's filter.
1905
- */
1906
- getFilter(layerId: string) {
1907
- return this.style.getFilter(layerId);
1908
- }
1909
-
1910
- /**
1911
- * Sets the value of a paint property in the specified style layer.
1912
- *
1913
- * @param {string} layerId The ID of the layer to set the paint property in.
1914
- * @param {string} name The name of the paint property to set.
1915
- * @param {*} value The value of the paint property to set.
1916
- * Must be of a type appropriate for the property, as defined in the [Mapbox Style Specification](https://www.mapbox.com/mapbox-gl-style-spec/).
1917
- * @param {Object} [options] Options object.
1918
- * @param {boolean} [options.validate=true] Whether to check if `value` conforms to the Mapbox GL Style Specification. Disabling validation is a performance optimization that should only be used if you have previously validated the values you will be passing to this function.
1919
- * @returns {Map} `this`
1920
- * @example
1921
- * map.setPaintProperty('my-layer', 'fill-color', '#faafee');
1922
- * @see [Change a layer's color with buttons](https://www.mapbox.com/mapbox-gl-js/example/color-switcher/)
1923
- * @see [Adjust a layer's opacity](https://www.mapbox.com/mapbox-gl-js/example/adjust-layer-opacity/)
1924
- * @see [Create a draggable point](https://www.mapbox.com/mapbox-gl-js/example/drag-a-point/)
1925
- */
1926
- setPaintProperty(layerId: string, name: string, value: any, options: StyleSetterOptions = {}) {
1927
- this.style.setPaintProperty(layerId, name, value, options);
1928
- return this._update(true);
1929
- }
1930
-
1931
- /**
1932
- * Returns the value of a paint property in the specified style layer.
1933
- *
1934
- * @param {string} layerId The ID of the layer to get the paint property from.
1935
- * @param {string} name The name of a paint property to get.
1936
- * @returns {*} The value of the specified paint property.
1937
- */
1938
- getPaintProperty(layerId: string, name: string) {
1939
- return this.style.getPaintProperty(layerId, name);
1940
- }
1941
-
1942
- /**
1943
- * Sets the value of a layout property in the specified style layer.
1944
- *
1945
- * @param {string} layerId The ID of the layer to set the layout property in.
1946
- * @param {string} name The name of the layout property to set.
1947
- * @param {*} value The value of the layout property. Must be of a type appropriate for the property, as defined in the [Mapbox Style Specification](https://www.mapbox.com/mapbox-gl-style-spec/).
1948
- * @param {Object} [options] Options object.
1949
- * @param {boolean} [options.validate=true] Whether to check if `value` conforms to the Mapbox GL Style Specification. Disabling validation is a performance optimization that should only be used if you have previously validated the values you will be passing to this function.
1950
- * @returns {Map} `this`
1951
- * @example
1952
- * map.setLayoutProperty('my-layer', 'visibility', 'none');
1953
- */
1954
- setLayoutProperty(layerId: string, name: string, value: any, options: StyleSetterOptions = {}) {
1955
- if (this.overlayLayersManager[layerId]) {
1956
- if (name === "visibility") {
1957
- if (value === "visible") {
1958
- value = true;
1959
- } else {
1960
- value = false;
1961
- }
1962
- this._setVisibility(this.overlayLayersManager[layerId], value);
1963
- this.style.fire('data', {dataType: 'style'});
1964
- }
1965
- return this;
1966
- }
1967
- this.style.setLayoutProperty(layerId, name, value, options);
1968
- this._update(true);
1969
- return this;
1970
- }
1971
-
1972
- /**
1973
- * Returns the value of a layout property in the specified style layer.
1974
- *
1975
- * @param {string} layerId The ID of the layer to get the layout property from.
1976
- * @param {string} name The name of the layout property to get.
1977
- * @returns {*} The value of the specified layout property.
1978
- */
1979
- getLayoutProperty(layerId: string, name: string) {
1980
- return this.style.getLayoutProperty(layerId, name);
1981
- }
1982
-
1983
- /**
1984
- * Sets the any combination of light values.
1985
- *
1986
- * @param light Light properties to set. Must conform to the [Mapbox Style Specification](https://www.mapbox.com/mapbox-gl-style-spec/#light).
1987
- * @param {Object} [options] Options object.
1988
- * @param {boolean} [options.validate=true] Whether to check if the filter conforms to the Mapbox GL Style Specification. Disabling validation is a performance optimization that should only be used if you have previously validated the values you will be passing to this function.
1989
- * @returns {Map} `this`
1990
- */
1991
- setLight(light: LightSpecification, options: StyleSetterOptions = {}) {
1992
- this._lazyInitEmptyStyle();
1993
- this.style.setLight(light, options);
1994
- return this._update(true);
1995
- }
1996
-
1997
- /**
1998
- * Returns the value of the light object.
1999
- *
2000
- * @returns {Object} light Light properties of the style.
2001
- */
2002
- getLight() {
2003
- return this.style.getLight();
2004
- }
2005
-
2006
- // eslint-disable-next-line jsdoc/require-returns
2007
- /**
2008
- * Sets the state of a feature. The `state` object is merged in with the existing state of the feature.
2009
- * Features are identified by their `id` attribute, which must be an integer or a string that can be
2010
- * cast to an integer.
2011
- *
2012
- * @param {Object} feature Feature identifier. Feature objects returned from
2013
- * {@link Map#queryRenderedFeatures} or event handlers can be used as feature identifiers.
2014
- * @param {string | number} feature.id Unique id of the feature.
2015
- * @param {string} feature.source The Id of the vector source or GeoJSON source for the feature.
2016
- * @param {string} [feature.sourceLayer] (optional) *For vector tile sources, the sourceLayer is
2017
- * required.*
2018
- * @param {Object} state A set of key-value pairs. The values should be valid JSON types.
2019
- *
2020
- * This method requires the `feature.id` attribute on data sets. For GeoJSON sources without
2021
- * feature ids, set the `generateId` option in the `GeoJSONSourceSpecification` to auto-assign them. This
2022
- * option assigns ids based on a feature's index in the source data. If you change feature data using
2023
- * `map.getSource('some id').setData(..)`, you may need to re-apply state taking into account updated `id` values.
2024
- * @see [Create a hover effect](https://docs.mapbox.com/mapbox-gl-js/example/hover-styles/)
2025
- */
2026
- setFeatureState(feature: { source: string; sourceLayer?: string; id: string | number; }, state: Object) {
2027
- this.style.setFeatureState(feature, state);
2028
- return this._update();
2029
- }
2030
-
2031
- // eslint-disable-next-line jsdoc/require-returns
2032
- /**
2033
- * Removes feature state, setting it back to the default behavior. If only
2034
- * source is specified, removes all states of that source. If
2035
- * target.id is also specified, removes all keys for that feature's state.
2036
- * If key is also specified, removes that key from that feature's state.
2037
- * Features are identified by their `id` attribute, which must be an integer or a string that can be
2038
- * cast to an integer.
2039
- * @param {Object} target Identifier of where to set state: can be a source, a feature, or a specific key of feature.
2040
- * Feature objects returned from {@link Map#queryRenderedFeatures} or event handlers can be used as feature identifiers.
2041
- * @param {string | number} target.id (optional) Unique id of the feature. Optional if key is not specified.
2042
- * @param {string} target.source The Id of the vector source or GeoJSON source for the feature.
2043
- * @param {string} [target.sourceLayer] (optional) *For vector tile sources, the sourceLayer is
2044
- * required.*
2045
- * @param {string} key (optional) The key in the feature state to reset.
2046
- */
2047
- removeFeatureState(target: { source: string; sourceLayer?: string; id?: string | number; }, key?: string) {
2048
- this.style.removeFeatureState(target, key);
2049
- return this._update();
2050
- }
2051
-
2052
- /**
2053
- * Gets the state of a feature.
2054
- * Features are identified by their `id` attribute, which must be an integer or a string that can be
2055
- * cast to an integer.
2056
- *
2057
- * @param {Object} feature Feature identifier. Feature objects returned from
2058
- * {@link Map#queryRenderedFeatures} or event handlers can be used as feature identifiers.
2059
- * @param {string | number} feature.id Unique id of the feature.
2060
- * @param {string} feature.source The Id of the vector source or GeoJSON source for the feature.
2061
- * @param {string} [feature.sourceLayer] (optional) *For vector tile sources, the sourceLayer is
2062
- * required.*
2063
- *
2064
- * @returns {Object} The state of the feature.
2065
- */
2066
- getFeatureState(feature: { source: string; sourceLayer?: string; id: string | number; }): any {
2067
- return this.style.getFeatureState(feature);
2068
- }
2069
-
2070
- /**
2071
- * Returns the map's containing HTML element.
2072
- *
2073
- * @returns {HTMLElement} The map's container.
2074
- */
2075
- getContainer() {
2076
- return this._container;
2077
- }
2078
-
2079
- /**
2080
- * Returns the HTML element containing the map's `<canvas>` element.
2081
- *
2082
- * If you want to add non-GL overlays to the map, you should append them to this element.
2083
- *
2084
- * This is the element to which event bindings for map interactivity (such as panning and zooming) are
2085
- * attached. It will receive bubbled events from child elements such as the `<canvas>`, but not from
2086
- * map controls.
2087
- *
2088
- * @returns {HTMLElement} The container of the map's `<canvas>`.
2089
- * @see [Create a draggable point](https://www.mapbox.com/mapbox-gl-js/example/drag-a-point/)
2090
- * @see [Highlight features within a bounding box](https://www.mapbox.com/mapbox-gl-js/example/using-box-queryrenderedfeatures/)
2091
- */
2092
- getCanvasContainer() {
2093
- return this._canvasContainer;
2094
- }
2095
-
2096
- /**
2097
- * Returns the map's `<canvas>` element.
2098
- *
2099
- * @returns {HTMLCanvasElement} The map's `<canvas>` element.
2100
- * @see [Measure distances](https://www.mapbox.com/mapbox-gl-js/example/measure/)
2101
- * @see [Display a popup on hover](https://www.mapbox.com/mapbox-gl-js/example/popup-on-hover/)
2102
- * @see [Center the map on a clicked symbol](https://www.mapbox.com/mapbox-gl-js/example/center-on-symbol/)
2103
- */
2104
- getCanvas() {
2105
- return this._canvas;
2106
- }
2107
-
2108
- _containerDimensions() {
2109
- let width = 0;
2110
- let height = 0;
2111
-
2112
- if (this._container) {
2113
- width = this._container.clientWidth || 400;
2114
- height = this._container.clientHeight || 300;
2115
- }
2116
-
2117
- return [width, height];
2118
- }
2119
-
2120
- _detectMissingCSS(): void {
2121
- const computedColor = window.getComputedStyle(this._missingCSSCanary).getPropertyValue('background-color');
2122
- if (computedColor !== 'rgb(250, 128, 114)') {
2123
- warnOnce('This page appears to be missing CSS declarations for ' +
2124
- 'Mapbox GL JS, which may cause the map to display incorrectly. ' +
2125
- 'Please ensure your page includes mapbox-gl.css, as described ' +
2126
- 'in https://www.mapbox.com/mapbox-gl-js/api/.');
2127
- }
2128
- }
2129
-
2130
- _setupContainer() {
2131
- const container = this._container;
2132
- container.classList.add('mapboxgl-map');
2133
-
2134
- const missingCSSCanary = this._missingCSSCanary = DOM.create('div', 'mapboxgl-canary', container);
2135
- missingCSSCanary.style.visibility = 'hidden';
2136
- this._detectMissingCSS();
2137
-
2138
- const canvasContainer = this._canvasContainer = DOM.create('div', 'mapboxgl-canvas-container', container);
2139
- if (this._interactive) {
2140
- canvasContainer.classList.add('mapboxgl-interactive');
2141
- }
2142
-
2143
- this._canvas = DOM.create('canvas', 'mapboxgl-canvas', canvasContainer);
2144
- this._canvas.addEventListener('webglcontextlost', this._contextLost, false);
2145
- this._canvas.addEventListener('webglcontextrestored', this._contextRestored, false);
2146
- this._canvas.setAttribute('tabindex', '0');
2147
- this._canvas.setAttribute('aria-label', 'Map');
2148
-
2149
- const dimensions = this._containerDimensions();
2150
- this._resizeCanvas(dimensions[0], dimensions[1]);
2151
-
2152
- const controlContainer = this._controlContainer = DOM.create('div', 'mapboxgl-control-container', container);
2153
- const positions = this._controlPositions = {};
2154
- ['top-left', 'top-right', 'bottom-left', 'bottom-right'].forEach((positionName) => {
2155
- positions[positionName] = DOM.create('div', `mapboxgl-ctrl-${positionName}`, controlContainer);
2156
- });
2157
- }
2158
-
2159
- _resizeCanvas(width: number, height: number) {
2160
- const pixelRatio = browser.devicePixelRatio || 1;
2161
-
2162
- // Request the required canvas size taking the pixelratio into account.
2163
- this._canvas.width = pixelRatio * width;
2164
- this._canvas.height = pixelRatio * height;
2165
-
2166
- // Maintain the same canvas size, potentially downscaling it for HiDPI displays
2167
- this._canvas.style.width = `${width}px`;
2168
- this._canvas.style.height = `${height}px`;
2169
- }
2170
-
2171
- _setupPainter() {
2172
- const attributes = extend({}, isSupported.webGLContextAttributes, {
2173
- failIfMajorPerformanceCaveat: this._failIfMajorPerformanceCaveat,
2174
- preserveDrawingBuffer: this._preserveDrawingBuffer,
2175
- antialias: this._antialias || false
2176
- });
2177
-
2178
- const gl = this._canvas.getContext('webgl', attributes) ||
2179
- this._canvas.getContext('experimental-webgl', attributes);
2180
-
2181
- if (!gl) {
2182
- this.fire(new ErrorEvent(new Error('Failed to initialize WebGL')));
2183
- return;
2184
- }
2185
-
2186
- this.painter = new Painter(gl, this.transform);
2187
-
2188
- webpSupported.testSupport(gl);
2189
- }
2190
-
2191
- _contextLost(event: *) {
2192
- event.preventDefault();
2193
- if (this._frame) {
2194
- this._frame.cancel();
2195
- this._frame = null;
2196
- }
2197
- this.fire(new Event('webglcontextlost', {originalEvent: event}));
2198
- }
2199
-
2200
- _contextRestored(event: *) {
2201
- this._setupPainter();
2202
- this.resize();
2203
- this._update();
2204
- this.fire(new Event('webglcontextrestored', {originalEvent: event}));
2205
- }
2206
-
2207
- /**
2208
- * Returns a Boolean indicating whether the map is fully loaded.
2209
- *
2210
- * Returns `false` if the style is not yet fully loaded,
2211
- * or if there has been a change to the sources or style that
2212
- * has not yet fully loaded.
2213
- *
2214
- * @returns {boolean} A Boolean indicating whether the map is fully loaded.
2215
- */
2216
- loaded() {
2217
- return !this._styleDirty && !this._sourcesDirty && !!this.style && this.style.loaded();
2218
- }
2219
-
2220
- /**
2221
- * Update this map's style and sources, and re-render the map.
2222
- *
2223
- * @param {boolean} updateStyle mark the map's style for reprocessing as
2224
- * well as its sources
2225
- * @returns {Map} this
2226
- * @private
2227
- */
2228
- _update(updateStyle?: boolean) {
2229
- if (!this.style) return this;
2230
-
2231
- this._styleDirty = this._styleDirty || updateStyle;
2232
- this._sourcesDirty = true;
2233
- this.triggerRepaint();
2234
-
2235
- return this;
2236
- }
2237
-
2238
- /**
2239
- * Request that the given callback be executed during the next render
2240
- * frame. Schedule a render frame if one is not already scheduled.
2241
- * @returns An id that can be used to cancel the callback
2242
- * @private
2243
- */
2244
- _requestRenderFrame(callback: () => void): TaskID {
2245
- this._update();
2246
- return this._renderTaskQueue.add(callback);
2247
- }
2248
-
2249
- _cancelRenderFrame(id: TaskID) {
2250
- this._renderTaskQueue.remove(id);
2251
- }
2252
-
2253
- /**
2254
- * Call when a (re-)render of the map is required:
2255
- * - The style has changed (`setPaintProperty()`, etc.)
2256
- * - Source data has changed (e.g. tiles have finished loading)
2257
- * - The map has is moving (or just finished moving)
2258
- * - A transition is in progress
2259
- *
2260
- * @returns {Map} this
2261
- * @private
2262
- */
2263
- _render() {
2264
- let gpuTimer, frameStartTime = 0;
2265
- const extTimerQuery = this.painter.context.extTimerQuery;
2266
- if (this.listens('gpu-timing-frame')) {
2267
- gpuTimer = extTimerQuery.createQueryEXT();
2268
- extTimerQuery.beginQueryEXT(extTimerQuery.TIME_ELAPSED_EXT, gpuTimer);
2269
- frameStartTime = browser.now();
2270
- }
2271
-
2272
- // A custom layer may have used the context asynchronously. Mark the state as dirty.
2273
- this.painter.context.setDirty();
2274
- this.painter.setBaseState();
2275
-
2276
- this._renderTaskQueue.run();
2277
-
2278
- let crossFading = false;
2279
-
2280
- // If the style has changed, the map is being zoomed, or a transition or fade is in progress:
2281
- // - Apply style changes (in a batch)
2282
- // - Recalculate paint properties.
2283
- if (this.style && this._styleDirty) {
2284
- this._styleDirty = false;
2285
-
2286
- const zoom = this.transform.zoom;
2287
- const now = browser.now();
2288
- this.style.zoomHistory.update(zoom, now);
2289
-
2290
- const parameters = new EvaluationParameters(zoom, {
2291
- now,
2292
- fadeDuration: this._fadeDuration,
2293
- zoomHistory: this.style.zoomHistory,
2294
- transition: this.style.getTransition()
2295
- });
2296
-
2297
- const factor = parameters.crossFadingFactor();
2298
- if (factor !== 1 || factor !== this._crossFadingFactor) {
2299
- crossFading = true;
2300
- this._crossFadingFactor = factor;
2301
- }
2302
-
2303
- this.style.update(parameters);
2304
- }
2305
-
2306
- // If we are in _render for any reason other than an in-progress paint
2307
- // transition, update source caches to check for and load any tiles we
2308
- // need for the current transform
2309
- if (this.style && this._sourcesDirty) {
2310
- this._sourcesDirty = false;
2311
- this.style._updateSources(this.transform);
2312
- }
2313
-
2314
- this._placementDirty = this.style && this.style._updatePlacement(this.painter.transform, this.showCollisionBoxes, this._fadeDuration, this._crossSourceCollisions);
2315
-
2316
- // Actually draw
2317
- this.painter.render(this.style, {
2318
- showTileBoundaries: this.showTileBoundaries,
2319
- showOverdrawInspector: this._showOverdrawInspector,
2320
- rotating: this.isRotating(),
2321
- zooming: this.isZooming(),
2322
- moving: this.isMoving(),
2323
- fadeDuration: this._fadeDuration,
2324
- showPadding: this.showPadding,
2325
- gpuTiming: !!this.listens('gpu-timing-layer'),
2326
- });
2327
-
2328
- this.fire(new Event('render'));
2329
-
2330
- if (this.loaded() && !this._loaded) {
2331
- this._loaded = true;
2332
- PerformanceUtils.mark(PerformanceMarkers.load);
2333
- this.fire(new Event('load'));
2334
- }
2335
-
2336
- if (this.style && (this.style.hasTransitions() || crossFading)) {
2337
- this._styleDirty = true;
2338
- }
2339
-
2340
- if (this.style && !this._placementDirty) {
2341
- // Since no fade operations are in progress, we can release
2342
- // all tiles held for fading. If we didn't do this, the tiles
2343
- // would just sit in the SourceCaches until the next render
2344
- this.style._releaseSymbolFadeTiles();
2345
- }
2346
-
2347
- if (this.listens('gpu-timing-frame')) {
2348
- const renderCPUTime = browser.now() - frameStartTime;
2349
- extTimerQuery.endQueryEXT(extTimerQuery.TIME_ELAPSED_EXT, gpuTimer);
2350
- setTimeout(() => {
2351
- const renderGPUTime = extTimerQuery.getQueryObjectEXT(gpuTimer, extTimerQuery.QUERY_RESULT_EXT) / (1000 * 1000);
2352
- extTimerQuery.deleteQueryEXT(gpuTimer);
2353
- this.fire(new Event('gpu-timing-frame', {
2354
- cpuTime: renderCPUTime,
2355
- gpuTime: renderGPUTime
2356
- }));
2357
- }, 50); // Wait 50ms to give time for all GPU calls to finish before querying
2358
- }
2359
-
2360
- if (this.listens('gpu-timing-layer')) {
2361
- // Resetting the Painter's per-layer timing queries here allows us to isolate
2362
- // the queries to individual frames.
2363
- const frameLayerQueries = this.painter.collectGpuTimers();
2364
-
2365
- setTimeout(() => {
2366
- const renderedLayerTimes = this.painter.queryGpuTimers(frameLayerQueries);
2367
-
2368
- this.fire(new Event('gpu-timing-layer', {
2369
- layerTimes: renderedLayerTimes
2370
- }));
2371
- }, 50); // Wait 50ms to give time for all GPU calls to finish before querying
2372
- }
2373
-
2374
- // Schedule another render frame if it's needed.
2375
- //
2376
- // Even though `_styleDirty` and `_sourcesDirty` are reset in this
2377
- // method, synchronous events fired during Style#update or
2378
- // Style#_updateSources could have caused them to be set again.
2379
- const somethingDirty = this._sourcesDirty || this._styleDirty || this._placementDirty;
2380
- if (somethingDirty || this._repaint) {
2381
- this.triggerRepaint();
2382
- } else if (!this.isMoving() && this.loaded()) {
2383
- if (!this._fullyLoaded) {
2384
- this._fullyLoaded = true;
2385
- PerformanceUtils.mark(PerformanceMarkers.fullLoad);
2386
- }
2387
- this.fire(new Event('idle'));
2388
- }
2389
-
2390
- return this;
2391
- }
2392
-
2393
- /**
2394
- * Clean up and release all internal resources associated with this map.
2395
- *
2396
- * This includes DOM elements, event bindings, web workers, and WebGL resources.
2397
- *
2398
- * Use this method when you are done using the map and wish to ensure that it no
2399
- * longer consumes browser resources. Afterwards, you must not call any other
2400
- * methods on the map.
2401
- */
2402
- remove() {
2403
- if (this._hash) this._hash.remove();
2404
-
2405
- for (const control of this._controls) control.onRemove(this);
2406
- this._controls = [];
2407
-
2408
- if (this._frame) {
2409
- this._frame.cancel();
2410
- this._frame = null;
2411
- }
2412
- this._renderTaskQueue.clear();
2413
- this.painter.destroy();
2414
- this.setStyle(null);
2415
- if (typeof window !== 'undefined') {
2416
- window.removeEventListener('resize', this._onWindowResize, false);
2417
- window.removeEventListener('online', this._onWindowOnline, false);
2418
- }
2419
-
2420
- const extension = this.painter.context.gl.getExtension('WEBGL_lose_context');
2421
- if (extension) extension.loseContext();
2422
- removeNode(this._canvasContainer);
2423
- removeNode(this._controlContainer);
2424
- removeNode(this._missingCSSCanary);
2425
- this._container.classList.remove('mapboxgl-map');
2426
-
2427
- PerformanceUtils.clearMetrics();
2428
- this.fire(new Event('remove'));
2429
- }
2430
-
2431
- /**
2432
- * Trigger the rendering of a single frame. Use this method with custom layers to
2433
- * repaint the map when the layer changes. Calling this multiple times before the
2434
- * next frame is rendered will still result in only a single frame being rendered.
2435
- */
2436
- triggerRepaint() {
2437
- if (this.style && !this._frame) {
2438
- this._frame = browser.frame((paintStartTimestamp: number) => {
2439
- PerformanceUtils.frame(paintStartTimestamp);
2440
- this._frame = null;
2441
- this._render();
2442
- });
2443
- }
2444
- }
2445
-
2446
- _onWindowOnline() {
2447
- this._update();
2448
- }
2449
-
2450
- _onWindowResize(event: Event) {
2451
- if (this._trackResize) {
2452
- this.resize({originalEvent: event})._update();
2453
- }
2454
- }
2455
-
2456
- /**
2457
- * Gets and sets a Boolean indicating whether the map will render an outline
2458
- * around each tile and the tile ID. These tile boundaries are useful for
2459
- * debugging.
2460
- *
2461
- * The uncompressed file size of the first vector source is drawn in the top left
2462
- * corner of each tile, next to the tile ID.
2463
- *
2464
- * @name showTileBoundaries
2465
- * @type {boolean}
2466
- * @instance
2467
- * @memberof Map
2468
- */
2469
- get showTileBoundaries(): boolean { return !!this._showTileBoundaries; }
2470
- set showTileBoundaries(value: boolean) {
2471
- if (this._showTileBoundaries === value) return;
2472
- this._showTileBoundaries = value;
2473
- this._update();
2474
- }
2475
-
2476
- /**
2477
- * Gets and sets a Boolean indicating whether the map will visualize
2478
- * the padding offsets.
2479
- *
2480
- * @name showPadding
2481
- * @type {boolean}
2482
- * @instance
2483
- * @memberof Map
2484
- */
2485
- get showPadding(): boolean { return !!this._showPadding; }
2486
- set showPadding(value: boolean) {
2487
- if (this._showPadding === value) return;
2488
- this._showPadding = value;
2489
- this._update();
2490
- }
2491
-
2492
- /**
2493
- * Gets and sets a Boolean indicating whether the map will render boxes
2494
- * around all symbols in the data source, revealing which symbols
2495
- * were rendered or which were hidden due to collisions.
2496
- * This information is useful for debugging.
2497
- *
2498
- * @name showCollisionBoxes
2499
- * @type {boolean}
2500
- * @instance
2501
- * @memberof Map
2502
- */
2503
- get showCollisionBoxes(): boolean { return !!this._showCollisionBoxes; }
2504
- set showCollisionBoxes(value: boolean) {
2505
- if (this._showCollisionBoxes === value) return;
2506
- this._showCollisionBoxes = value;
2507
- if (value) {
2508
- // When we turn collision boxes on we have to generate them for existing tiles
2509
- // When we turn them off, there's no cost to leaving existing boxes in place
2510
- this.style._generateCollisionBoxes();
2511
- } else {
2512
- // Otherwise, call an update to remove collision boxes
2513
- this._update();
2514
- }
2515
- }
2516
-
2517
- /*
2518
- * Gets and sets a Boolean indicating whether the map should color-code
2519
- * each fragment to show how many times it has been shaded.
2520
- * White fragments have been shaded 8 or more times.
2521
- * Black fragments have been shaded 0 times.
2522
- * This information is useful for debugging.
2523
- *
2524
- * @name showOverdraw
2525
- * @type {boolean}
2526
- * @instance
2527
- * @memberof Map
2528
- */
2529
- get showOverdrawInspector(): boolean { return !!this._showOverdrawInspector; }
2530
- set showOverdrawInspector(value: boolean) {
2531
- if (this._showOverdrawInspector === value) return;
2532
- this._showOverdrawInspector = value;
2533
- this._update();
2534
- }
2535
-
2536
- /**
2537
- * Gets and sets a Boolean indicating whether the map will
2538
- * continuously repaint. This information is useful for analyzing performance.
2539
- *
2540
- * @name repaint
2541
- * @type {boolean}
2542
- * @instance
2543
- * @memberof Map
2544
- */
2545
- get repaint(): boolean { return !!this._repaint; }
2546
- set repaint(value: boolean) {
2547
- if (this._repaint !== value) {
2548
- this._repaint = value;
2549
- this.triggerRepaint();
2550
- }
2551
- }
2552
- // show vertices
2553
- get vertices(): boolean { return !!this._vertices; }
2554
- set vertices(value: boolean) { this._vertices = value; this._update(); }
2555
-
2556
- // for cache browser tests
2557
- _setCacheLimits(limit: number, checkThreshold: number) {
2558
- setCacheLimits(limit, checkThreshold);
2559
- }
2560
-
2561
- initCRS(code) {
2562
- if (code && typeof code === "string" && !(code = CRS.get(code))) {
2563
- throw new Error('crs ' + code + ' is not define');
2564
- }
2565
- return code || CRS.EPSG3857;
2566
- }
2567
-
2568
- getCRS() {
2569
- return this.crs;
2570
- }
2571
-
2572
- setCRS(crs) {
2573
- if (crs !== CRS.EPSG3857) {
2574
- this._tileExtent = [-20037508.3427892, -20037508.3427892, 20037508.3427892, 20037508.3427892];
2575
- this._mapCRS = crs;
2576
- const extent = crs.getExtent();
2577
- if (extent && Array.isArray(extent) && extent.length === 4) {
2578
- this._tileExtent = extent;
2579
- const width = this._tileExtent[2] - this._tileExtent[0],
2580
- height = this._tileExtent[3] - this._tileExtent[1],
2581
- centerX = (this._tileExtent[2] + this._tileExtent[0]) / 2, // 0
2582
- centerY = (this._tileExtent[3] + this._tileExtent[1]) / 2, // -90
2583
- originX = this._tileExtent[0], // -180
2584
- originY = this._tileExtent[3]; // 90
2585
- RasterTileSource.prototype.getMeterPerMapUnit = function (mapUnit) {
2586
- let meters = 1;
2587
- if (mapUnit === "degree" || mapUnit === "degrees" || mapUnit === "d") {
2588
- meters = 2 * Math.PI * 6378137 / 360;
2589
- } else if (mapUnit === "kilometer" || mapUnit === "km") {
2590
- meters = .001;
2591
- } else if (mapUnit === "inch") {
2592
- meters = 1 / .025399999918;
2593
- } else {
2594
- meters = .3048;
2595
- }
2596
- return meters;
2597
- };
2598
- RasterTileSource.prototype.getResolution = function (t, e) {
2599
- if (!this._resolutions[t]) {
2600
- const i = Math.pow(2, t);
2601
- this._resolutions[t] = width / i / e;
2602
- }
2603
- return this._resolutions[t];
2604
- };
2605
- RasterTileSource.prototype.getScale = function (t, i) {
2606
- if (!this._scales[t]) {
2607
- const r = 96 * this.getResolution(t, i) * (1 / .0254) * this.getMeterPerMapUnit(crs.getUnit());
2608
- this._scales[t] = 1 / r;
2609
- }
2610
- return this._scales[t];
2611
- };
2612
- VectorTileSource.prototype.getMeterPerMapUnit = function (mapUnit) {
2613
- let meters = 1;
2614
- if (mapUnit === "degree" || mapUnit === "degrees" || mapUnit === "d") {
2615
- meters = 2 * Math.PI * 6378137 / 360;
2616
- } else if (mapUnit === "kilometer" || mapUnit === "km") {
2617
- meters = .001;
2618
- } else if (mapUnit === "inch") {
2619
- meters = 1 / .025399999918;
2620
- } else {
2621
- meters = .3048;
2622
- }
2623
- return meters;
2624
- };
2625
- VectorTileSource.prototype.getResolution = function (t, e) {
2626
- if (!this._resolutions[t]) {
2627
- const i = Math.pow(2, t);
2628
- this._resolutions[t] = width / i / e;
2629
- }
2630
- return this._resolutions[t];
2631
- };
2632
- VectorTileSource.prototype.getScale = function (t, i) {
2633
- if (!this._scales[t]) {
2634
- const r = 96 * this.getResolution(t, i) * (1 / .0254) * this.getMeterPerMapUnit(crs.getUnit());
2635
- this._scales[t] = 1 / r;
2636
- }
2637
- return this._scales[t];
2638
- };
2639
- GeoJSONSource.prototype.getMeterPerMapUnit = function (mapUnit) {
2640
- let meters = 1;
2641
- if (mapUnit === "degree" || mapUnit === "degrees" || mapUnit === "d") {
2642
- meters = 2 * Math.PI * 6378137 / 360;
2643
- } else if (mapUnit === "kilometer" || mapUnit === "km") {
2644
- meters = .001;
2645
- } else if (mapUnit === "inch") {
2646
- meters = 1 / .025399999918;
2647
- } else {
2648
- meters = .3048;
2649
- }
2650
- return meters;
2651
- };
2652
- GeoJSONSource.prototype.getResolution = function (t, e) {
2653
- if (!this._resolutions[t]) {
2654
- const i = Math.pow(2, t);
2655
- this._resolutions[t] = width / i / e;
2656
- }
2657
- return this._resolutions[t];
2658
- };
2659
- GeoJSONSource.prototype.getScale = function (t, i) {
2660
- if (!this._scales[t]) {
2661
- const r = 96 * this.getResolution(t, i) * (1 / .0254) * this.getMeterPerMapUnit(crs.getUnit());
2662
- this._scales[t] = 1 / r;
2663
- }
2664
- return this._scales[t];
2665
- };
2666
- GeoJSONSource.prototype.getCrs = function (t, i) {
2667
- return 'EPSG:4326';
2668
- };
2669
-
2670
- CanonicalTileID.prototype.getTileBBox = function () {
2671
- const scale = Math.max(width, height) / Math.pow(2, this.z);
2672
- const left = scale * this.x + extent[0];
2673
- const right = scale * (this.x + 1) + extent[0];
2674
- const top = extent[3] - scale * this.y;
2675
- const bottom = extent[3] - scale * (this.y + 1);
2676
- const bbox = left + "," + bottom + "," + right + "," + top;
2677
- return bbox;
2678
- };
2679
-
2680
- CanonicalTileID.prototype.getViewBounds = function () {
2681
- const t = Math.pow(2, this.z);
2682
- return '{"leftBottom":{"x":' + (extent[0] + width * this.x / t) + ',"y":' + (extent[3] - height * (this.y + 1) / t) + '},"rightTop":{"x":' + (extent[0] + width * (this.x + 1) / t) + ',"y": ' + (extent[3] - height * this.y / t) + "}}";
2683
- };
2684
-
2685
- CanonicalTileID.prototype.getCRS = function() {
2686
- return CRS.EPSG4326;
2687
- };
2688
-
2689
- Transform.prototype.lngX = function (lng: number) {
2690
- return (lng - originX) * this.worldSize / width;
2691
- };
2692
-
2693
- Transform.prototype.latY = function (lat: number) {
2694
- return (originY - lat) * this.worldSize / height;
2695
- };
2696
-
2697
- Transform.prototype.xLng = function (lng: number) {
2698
- return lng * width / this.worldSize + originX;
2699
- };
2700
-
2701
- Transform.prototype.yLat = function (lat: number) {
2702
- return originY - lat * height / this.worldSize;
2703
- };
2704
- TileBounds.prototype.contains = function (tileID: CanonicalTileID) {
2705
- const e = Math.pow(2, tileID.z);
2706
- const level = {
2707
- minX: Math.floor((this.bounds.getWest() - originX) * e / width),
2708
- minY: Math.floor((originY - this.bounds.getNorth()) * e / height),
2709
- maxX: Math.ceil((this.bounds.getEast() - originX) * e / width),
2710
- maxY: Math.ceil((originY - this.bounds.getSouth()) * e / height)
2711
- };
2712
- const hit = tileID.x >= level.minX && tileID.x < level.maxX && tileID.y >= level.minY && tileID.y < level.maxY;
2713
- return hit;
2714
- };
2715
- GeoJSONFeature.prototype.yLat = function (t, e) {
2716
- let reuslt = originY - t * height / e;
2717
- return reuslt;
2718
- };
2719
- GeoJSONFeature.prototype.latY = function (lat: number) {
2720
- return (originY - lat) * this.worldSize / height;
2721
- };
2722
- if (this.updateTransform) {
2723
- this.mercatorZfromAltitude = mercatorZfromAltitude;
2724
- this.updateTransform(crs.getUnit(), originX, originY, centerX, centerY, width, height);
2725
- }
2726
- }
2727
- }
2728
- }
2729
-
2730
- updateTransform(units, originX, originY, centerX, centerY, width, height) {
2731
- this.transform.units = units;
2732
- this.transform.latRange = [this._tileExtent[1], this._tileExtent[3]]; // [-270. 90]
2733
- this.transform.lngRange = [this._tileExtent[0], this._tileExtent[2]]; // [-180. 180]
2734
- const transform = this.transform;
2735
- const mercatorZfromAltitude = this.mercatorZfromAltitude;
2736
- MercatorCoordinate.fromLngLat = function (lngLatLike, altitude) {
2737
- altitude = altitude || 0;
2738
- const lngLat = LngLat.convert(lngLatLike);
2739
- if (lngLat.lng && lngLat.lat) {
2740
- return new MercatorCoordinate(
2741
- (lngLat.lng - originX) / width,
2742
- (originY - lngLat.lat) / height,
2743
- mercatorZfromAltitude(altitude, lngLat.lat));
2744
- } else {
2745
- return new MercatorCoordinate(
2746
- mercatorXfromLng(0),
2747
- mercatorYfromLat(0),
2748
- 0
2749
- );
2750
- }
2751
- };
2752
- MercatorCoordinate.prototype.toLngLat = function () {
2753
- // console.log('toLngLat', this.x * width + originX, originY - this.y * height)
2754
- const lat = originY - this.y * height;
2755
- if (lat <= 90 && lat >= -90) { //不在范围内会报错
2756
- return new LngLat(
2757
- this.x * width + originX,
2758
- originY - this.y * height);
2759
- }
2760
- //return new LngLat(360 * this.x - 180, latFromMercatorY(this.y))
2761
- };
2762
- this.customConvertPoint = window.URL.createObjectURL(new Blob(['customConvertPoint = {projectX:function(x){return (x - ' + centerX + ') / ' + width + ' + 0.5},projectY:function(y){y = 0.5 - ((y - ' + centerY + ') / ' + height + ');return y < 0 ? 0 : y > 1 ? 1 : y;},toY:function(y){return (0.5-y)*' + height + '+' + centerY + ';}}'], {type: "text/javascript"}));
2763
- }
2764
-
2765
- /**
2766
- * The version of Mapbox GL JS in use as specified in package.json, CHANGELOG.md, and the GitHub release.
2767
- *
2768
- * @name version
2769
- * @instance
2770
- * @memberof Map
2771
- * @var {string} version
2772
- */
2773
-
2774
- get version(): string { return version; }
2775
- }
2776
-
2777
- export default Map;
2778
-
2779
- function removeNode(node) {
2780
- if (node.parentNode) {
2781
- node.parentNode.removeChild(node);
2782
- }
2783
- }
2784
-
2785
- /**
2786
- * Interface for interactive controls added to the map. This is a
2787
- * specification for implementers to model: it is not
2788
- * an exported method or class.
2789
- *
2790
- * Controls must implement `onAdd` and `onRemove`, and must own an
2791
- * element, which is often a `div` element. To use Mapbox GL JS's
2792
- * default control styling, add the `mapboxgl-ctrl` class to your control's
2793
- * node.
2794
- *
2795
- * @interface IControl
2796
- * @example
2797
- * // Control implemented as ES6 class
2798
- * class HelloWorldControl {
2799
- * onAdd(map) {
2800
- * this._map = map;
2801
- * this._container = document.createElement('div');
2802
- * this._container.className = 'mapboxgl-ctrl';
2803
- * this._container.textContent = 'Hello, world';
2804
- * return this._container;
2805
- * }
2806
- *
2807
- * onRemove() {
2808
- * this._container.parentNode.removeChild(this._container);
2809
- * this._map = undefined;
2810
- * }
2811
- * }
2812
- *
2813
- * // Control implemented as ES5 prototypical class
2814
- * function HelloWorldControl() { }
2815
- *
2816
- * HelloWorldControl.prototype.onAdd = function(map) {
2817
- * this._map = map;
2818
- * this._container = document.createElement('div');
2819
- * this._container.className = 'mapboxgl-ctrl';
2820
- * this._container.textContent = 'Hello, world';
2821
- * return this._container;
2822
- * };
2823
- *
2824
- * HelloWorldControl.prototype.onRemove = function () {
2825
- * this._container.parentNode.removeChild(this._container);
2826
- * this._map = undefined;
2827
- * };
2828
- */
2829
-
2830
- /**
2831
- * Register a control on the map and give it a chance to register event listeners
2832
- * and resources. This method is called by {@link Map#addControl}
2833
- * internally.
2834
- *
2835
- * @function
2836
- * @memberof IControl
2837
- * @instance
2838
- * @name onAdd
2839
- * @param {Map} map the Map this control will be added to
2840
- * @returns {HTMLElement} The control's container element. This should
2841
- * be created by the control and returned by onAdd without being attached
2842
- * to the DOM: the map will insert the control's element into the DOM
2843
- * as necessary.
2844
- */
2845
-
2846
- /**
2847
- * Unregister a control on the map and give it a chance to detach event listeners
2848
- * and resources. This method is called by {@link Map#removeControl}
2849
- * internally.
2850
- *
2851
- * @function
2852
- * @memberof IControl
2853
- * @instance
2854
- * @name onRemove
2855
- * @param {Map} map the Map this control will be removed from
2856
- * @returns {undefined} there is no required return value for this method
2857
- */
2858
-
2859
- /**
2860
- * Optionally provide a default position for this control. If this method
2861
- * is implemented and {@link Map#addControl} is called without the `position`
2862
- * parameter, the value returned by getDefaultPosition will be used as the
2863
- * control's position.
2864
- *
2865
- * @function
2866
- * @memberof IControl
2867
- * @instance
2868
- * @name getDefaultPosition
2869
- * @returns {string} a control position, one of the values valid in addControl.
2870
- */
2871
-
2872
- /**
2873
- * A [`Point` geometry](https://github.com/mapbox/point-geometry) object, which has
2874
- * `x` and `y` properties representing screen coordinates in pixels.
2875
- *
2876
- * @typedef {Object} Point
2877
- */
2878
-
2879
- /**
2880
- * A {@link Point} or an array of two numbers representing `x` and `y` screen coordinates in pixels.
2881
- *
2882
- * @typedef {(Point | Array<number>)} PointLike
2883
- */