-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
map.js
executable file
·1910 lines (1719 loc) · 79.3 KB
/
map.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// @flow
import { extend, bindAll, warnOnce, uniqueId } from '../util/util';
import browser from '../util/browser';
import window from '../util/window';
const { HTMLImageElement, HTMLElement } = window;
import DOM from '../util/dom';
import { getImage, ResourceType } from '../util/ajax';
import Style from '../style/style';
import EvaluationParameters from '../style/evaluation_parameters';
import Painter from '../render/painter';
import Transform from '../geo/transform';
import Hash from './hash';
import bindHandlers from './bind_handlers';
import Camera from './camera';
import LngLat from '../geo/lng_lat';
import LngLatBounds from '../geo/lng_lat_bounds';
import Point from '@mapbox/point-geometry';
import AttributionControl from './control/attribution_control';
import LogoControl from './control/logo_control';
import isSupported from '@mapbox/mapbox-gl-supported';
import { RGBAImage } from '../util/image';
import { Event, ErrorEvent } from '../util/evented';
import { MapMouseEvent } from './events';
import TaskQueue from '../util/task_queue';
import type {PointLike} from '@mapbox/point-geometry';
import type {LngLatLike} from '../geo/lng_lat';
import type {LngLatBoundsLike} from '../geo/lng_lat_bounds';
import type {RequestParameters} from '../util/ajax';
import type {StyleOptions} from '../style/style';
import type {MapEvent, MapDataEvent} from './events';
import type {CustomLayerInterface} from '../style/style_layer/custom_style_layer';
import type ScrollZoomHandler from './handler/scroll_zoom';
import type BoxZoomHandler from './handler/box_zoom';
import type DragRotateHandler from './handler/drag_rotate';
import type DragPanHandler from './handler/drag_pan';
import type KeyboardHandler from './handler/keyboard';
import type DoubleClickZoomHandler from './handler/dblclick_zoom';
import type TouchZoomRotateHandler from './handler/touch_zoom_rotate';
import type {TaskID} from '../util/task_queue';
import type {Cancelable} from '../types/cancelable';
import type {
LayerSpecification,
FilterSpecification,
StyleSpecification,
LightSpecification,
SourceSpecification
} from '../style-spec/types';
type ControlPosition = 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';
/* eslint-disable no-use-before-define */
type IControl = {
onAdd(map: Map): HTMLElement;
onRemove(map: Map): void;
+getDefaultPosition?: () => ControlPosition;
}
/* eslint-enable no-use-before-define */
type ResourceTypeEnum = $Keys<typeof ResourceType>;
export type RequestTransformFunction = (url: string, resourceType?: ResourceTypeEnum) => RequestParameters;
type MapOptions = {
hash?: boolean,
interactive?: boolean,
container: HTMLElement | string,
bearingSnap?: number,
attributionControl?: boolean,
customAttribution?: string | Array<string>,
logoPosition?: ControlPosition,
failIfMajorPerformanceCaveat?: boolean,
preserveDrawingBuffer?: boolean,
refreshExpiredTiles?: boolean,
maxBounds?: LngLatBoundsLike,
scrollZoom?: boolean,
minZoom?: ?number,
maxZoom?: ?number,
boxZoom?: boolean,
dragRotate?: boolean,
dragPan?: boolean,
keyboard?: boolean,
doubleClickZoom?: boolean,
touchZoomRotate?: boolean,
trackResize?: boolean,
center?: LngLatLike,
zoom?: number,
bearing?: number,
pitch?: number,
renderWorldCopies?: boolean,
maxTileCacheSize?: number,
transformRequest?: RequestTransformFunction
};
const defaultMinZoom = 0;
const defaultMaxZoom = 22;
const defaultOptions = {
center: [0, 0],
zoom: 0,
bearing: 0,
pitch: 0,
minZoom: defaultMinZoom,
maxZoom: defaultMaxZoom,
interactive: true,
scrollZoom: true,
boxZoom: true,
dragRotate: true,
dragPan: true,
keyboard: true,
doubleClickZoom: true,
touchZoomRotate: true,
bearingSnap: 7,
clickTolerance: 3,
hash: false,
attributionControl: true,
failIfMajorPerformanceCaveat: false,
preserveDrawingBuffer: false,
trackResize: true,
renderWorldCopies: true,
refreshExpiredTiles: true,
maxTileCacheSize: null,
transformRequest: null,
fadeDuration: 300,
crossSourceCollisions: true
};
/**
* The `Map` object represents the map on your page. It exposes methods
* and properties that enable you to programmatically change the map,
* and fires events as users interact with it.
*
* You create a `Map` by specifying a `container` and other options.
* Then Mapbox GL JS initializes the map on the page and returns your `Map`
* object.
*
* @extends Evented
* @param {Object} options
* @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.
* @param {number} [options.minZoom=0] The minimum zoom level of the map (0-24).
* @param {number} [options.maxZoom=22] The maximum zoom level of the map (0-24).
* @param {Object|string} [options.style] The map's Mapbox style. This must be an a JSON object conforming to
* the schema described in the [Mapbox Style Specification](https://mapbox.com/mapbox-gl-style-spec/), or a URL to
* such JSON.
*
* To load a style from the Mapbox API, you can use a URL of the form `mapbox://styles/:owner/:style`,
* where `:owner` is your Mapbox account name and `:style` is the style ID. Or you can use one of the following
* [the predefined Mapbox styles](https://www.mapbox.com/maps/):
*
* * `mapbox://styles/mapbox/streets-v10`
* * `mapbox://styles/mapbox/outdoors-v10`
* * `mapbox://styles/mapbox/light-v9`
* * `mapbox://styles/mapbox/dark-v9`
* * `mapbox://styles/mapbox/satellite-v9`
* * `mapbox://styles/mapbox/satellite-streets-v10`
* * `mapbox://styles/mapbox/navigation-preview-day-v2`
* * `mapbox://styles/mapbox/navigation-preview-night-v2`
* * `mapbox://styles/mapbox/navigation-guidance-day-v2`
* * `mapbox://styles/mapbox/navigation-guidance-night-v2`
*
* 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-v9?optimize=true`.
* Learn more about style-optimized vector tiles in our [API documentation](https://www.mapbox.com/api-documentation/#retrieve-tiles).
*
* @param {boolean} [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.
* For example, `http://path/to/my/page.html#2.59/39.26/53.07/-24.1/60`.
* @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.
* @param {number} [options.bearingSnap=7] The threshold, measured in degrees, that determines when the map's
* bearing will snap to north. For example, with a `bearingSnap` of 7, if the user rotates
* the map within 7 degrees of north, the map will automatically snap to exact north.
* @param {boolean} [options.pitchWithRotate=true] If `false`, the map's pitch (tilt) control with "drag to rotate" interaction will be disabled.
* @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).
* @param {boolean} [options.attributionControl=true] If `true`, an {@link AttributionControl} will be added to the map.
* @param {string | Array<string>} [options.customAttribution] String or strings to show in an {@link AttributionControl}. Only applicable if `options.attributionControl` is `true`.
* @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`.
* @param {boolean} [options.failIfMajorPerformanceCaveat=false] If `true`, map creation will fail if the performance of Mapbox
* GL JS would be dramatically worse than expected (i.e. a software renderer would be used).
* @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.
* @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.
* @param {LngLatBoundsLike} [options.maxBounds] If set, the map will be constrained to the given bounds.
* @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}.
* @param {boolean} [options.boxZoom=true] If `true`, the "box zoom" interaction is enabled (see {@link BoxZoomHandler}).
* @param {boolean} [options.dragRotate=true] If `true`, the "drag to rotate" interaction is enabled (see {@link DragRotateHandler}).
* @param {boolean} [options.dragPan=true] If `true`, the "drag to pan" interaction is enabled (see {@link DragPanHandler}).
* @param {boolean} [options.keyboard=true] If `true`, keyboard shortcuts are enabled (see {@link KeyboardHandler}).
* @param {boolean} [options.doubleClickZoom=true] If `true`, the "double click to zoom" interaction is enabled (see {@link DoubleClickZoomHandler}).
* @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}.
* @param {boolean} [options.trackResize=true] If `true`, the map will automatically resize when the browser window resizes.
* @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.
* @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`.
* @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`.
* @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`.
* @param {LngLatBoundsLike} [options.bounds] The initial bounds of the map. If `bounds` is specified, it overrides `center` and `zoom` constructor options.
* @param {boolean} [options.renderWorldCopies=true] If `true`, multiple copies of the world will be rendered, when zoomed out.
* @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.
* @param {string} [options.localIdeographFontFamily=null] If specified, defines a CSS font-family
* for locally overriding generation of glyphs in the 'CJK Unified Ideographs' and 'Hangul Syllables' ranges.
* In these ranges, font settings from the map's style will be ignored, except for font-weight keywords (light/regular/medium/bold).
* 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))
* @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.
* Expected to return an object with a `url` property and optionally `headers` and `credentials` properties.
* @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.
* @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.
* @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.
* @example
* var map = new mapboxgl.Map({
* container: 'map',
* center: [-122.420679, 37.772537],
* zoom: 13,
* style: style_object,
* hash: true,
* transformRequest: (url, resourceType)=> {
* if(resourceType === 'Source' && url.startsWith('http://myHost')) {
* return {
* url: url.replace('http', 'https'),
* headers: { 'my-custom-header': true},
* credentials: 'include' // Include cookies for cross-origin requests
* }
* }
* }
* });
* @see [Display a map](https://www.mapbox.com/mapbox-gl-js/examples/)
*/
class Map extends Camera {
style: Style;
painter: Painter;
_container: HTMLElement;
_missingCSSCanary: HTMLElement;
_canvasContainer: HTMLElement;
_controlContainer: HTMLElement;
_controlPositions: {[string]: HTMLElement};
_interactive: ?boolean;
_showTileBoundaries: ?boolean;
_showCollisionBoxes: ?boolean;
_showOverdrawInspector: boolean;
_repaint: ?boolean;
_vertices: ?boolean;
_canvas: HTMLCanvasElement;
_transformRequest: RequestTransformFunction;
_maxTileCacheSize: number;
_frame: ?Cancelable;
_styleDirty: ?boolean;
_sourcesDirty: ?boolean;
_placementDirty: ?boolean;
_loaded: boolean;
_trackResize: boolean;
_preserveDrawingBuffer: boolean;
_failIfMajorPerformanceCaveat: boolean;
_refreshExpiredTiles: boolean;
_hash: Hash;
_delegatedListeners: any;
_fadeDuration: number;
_crossSourceCollisions: boolean;
_crossFadingFactor: number;
_collectResourceTiming: boolean;
_renderTaskQueue: TaskQueue;
_controls: Array<IControl>;
_mapId: number;
/**
* The map's {@link ScrollZoomHandler}, which implements zooming in and out with a scroll wheel or trackpad.
*/
scrollZoom: ScrollZoomHandler;
/**
* The map's {@link BoxZoomHandler}, which implements zooming using a drag gesture with the Shift key pressed.
*/
boxZoom: BoxZoomHandler;
/**
* The map's {@link DragRotateHandler}, which implements rotating the map while dragging with the right
* mouse button or with the Control key pressed.
*/
dragRotate: DragRotateHandler;
/**
* The map's {@link DragPanHandler}, which implements dragging the map with a mouse or touch gesture.
*/
dragPan: DragPanHandler;
/**
* The map's {@link KeyboardHandler}, which allows the user to zoom, rotate, and pan the map using keyboard
* shortcuts.
*/
keyboard: KeyboardHandler;
/**
* The map's {@link DoubleClickZoomHandler}, which allows the user to zoom by double clicking.
*/
doubleClickZoom: DoubleClickZoomHandler;
/**
* The map's {@link TouchZoomRotateHandler}, which allows the user to zoom or rotate the map with touch gestures.
*/
touchZoomRotate: TouchZoomRotateHandler;
constructor(options: MapOptions) {
options = extend({}, defaultOptions, options);
if (options.minZoom != null && options.maxZoom != null && options.minZoom > options.maxZoom) {
throw new Error(`maxZoom must be greater than minZoom`);
}
const transform = new Transform(options.minZoom, options.maxZoom, options.renderWorldCopies);
super(transform, options);
this._interactive = options.interactive;
this._maxTileCacheSize = options.maxTileCacheSize;
this._failIfMajorPerformanceCaveat = options.failIfMajorPerformanceCaveat;
this._preserveDrawingBuffer = options.preserveDrawingBuffer;
this._trackResize = options.trackResize;
this._bearingSnap = options.bearingSnap;
this._refreshExpiredTiles = options.refreshExpiredTiles;
this._fadeDuration = options.fadeDuration;
this._crossSourceCollisions = options.crossSourceCollisions;
this._crossFadingFactor = 1;
this._collectResourceTiming = options.collectResourceTiming;
this._renderTaskQueue = new TaskQueue();
this._controls = [];
this._mapId = uniqueId();
const transformRequestFn = options.transformRequest;
this._transformRequest = transformRequestFn ?
(url, type) => transformRequestFn(url, type) || ({ url }) :
(url) => ({ url });
if (typeof options.container === 'string') {
this._container = window.document.getElementById(options.container);
if (!this._container) {
throw new Error(`Container '${options.container}' not found.`);
}
} else if (options.container instanceof HTMLElement) {
this._container = options.container;
} else {
throw new Error(`Invalid type: 'container' must be a String or HTMLElement.`);
}
if (options.maxBounds) {
this.setMaxBounds(options.maxBounds);
}
bindAll([
'_onWindowOnline',
'_onWindowResize',
'_contextLost',
'_contextRestored'
], this);
this._setupContainer();
this._setupPainter();
if (this.painter === undefined) {
throw new Error(`Failed to initialize WebGL.`);
}
this.on('move', () => this._update(false));
this.on('zoom', () => this._update(true));
if (typeof window !== 'undefined') {
window.addEventListener('online', this._onWindowOnline, false);
window.addEventListener('resize', this._onWindowResize, false);
}
bindHandlers(this, options);
this._hash = options.hash && (new Hash()).addTo(this);
// don't set position from options if set through hash
if (!this._hash || !this._hash._onHashChange()) {
if (options.bounds) {
this.resize();
this.fitBounds(options.bounds, { duration: 0 });
} else {
this.jumpTo({
center: options.center,
zoom: options.zoom,
bearing: options.bearing,
pitch: options.pitch
});
}
}
this.resize();
if (options.style) this.setStyle(options.style, { localIdeographFontFamily: options.localIdeographFontFamily });
if (options.attributionControl)
this.addControl(new AttributionControl({ customAttribution: options.customAttribution }));
this.addControl(new LogoControl(), options.logoPosition);
this.on('style.load', () => {
if (this.transform.unmodified) {
this.jumpTo((this.style.stylesheet: any));
}
});
this.on('data', (event: MapDataEvent) => {
this._update(event.dataType === 'style');
this.fire(new Event(`${event.dataType}data`, event));
});
this.on('dataloading', (event: MapDataEvent) => {
this.fire(new Event(`${event.dataType}dataloading`, event));
});
}
/*
* Returns a unique number for this map instance which is used for the MapLoadEvent
* to make sure we only fire one event per instantiated map object.
* @private
* @returns {number}
*/
_getMapId() {
return this._mapId;
}
/**
* Adds a {@link IControl} to the map, calling `control.onAdd(this)`.
*
* @param {IControl} control The {@link IControl} to add.
* @param {string} [position] position on the map to which the control will be added.
* Valid values are `'top-left'`, `'top-right'`, `'bottom-left'`, and `'bottom-right'`. Defaults to `'top-right'`.
* @returns {Map} `this`
* @see [Display map navigation controls](https://www.mapbox.com/mapbox-gl-js/example/navigation/)
*/
addControl(control: IControl, position?: ControlPosition) {
if (position === undefined && control.getDefaultPosition) {
position = control.getDefaultPosition();
}
if (position === undefined) {
position = 'top-right';
}
if (!control || !control.onAdd) {
return this.fire(new ErrorEvent(new Error(
'Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.')));
}
const controlElement = control.onAdd(this);
this._controls.push(control);
const positionContainer = this._controlPositions[position];
if (position.indexOf('bottom') !== -1) {
positionContainer.insertBefore(controlElement, positionContainer.firstChild);
} else {
positionContainer.appendChild(controlElement);
}
return this;
}
/**
* Removes the control from the map.
*
* @param {IControl} control The {@link IControl} to remove.
* @returns {Map} `this`
*/
removeControl(control: IControl) {
if (!control || !control.onRemove) {
return this.fire(new ErrorEvent(new Error(
'Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.')));
}
const ci = this._controls.indexOf(control);
if (ci > -1) this._controls.splice(ci, 1);
control.onRemove(this);
return this;
}
/**
* Resizes the map according to the dimensions of its
* `container` element.
*
* This method must be called after the map's `container` is resized by another script,
* or when the map is shown after being initially hidden with CSS.
*
* @param eventData Additional properties to be added to event objects of events triggered by this method.
* @returns {Map} `this`
*/
resize(eventData?: Object) {
const dimensions = this._containerDimensions();
const width = dimensions[0];
const height = dimensions[1];
this._resizeCanvas(width, height);
this.transform.resize(width, height);
this.painter.resize(width, height);
this.fire(new Event('movestart', eventData))
.fire(new Event('move', eventData))
.fire(new Event('resize', eventData))
.fire(new Event('moveend', eventData));
return this;
}
/**
* Returns the map's geographical bounds. When the bearing or pitch is non-zero, the visible region is not
* an axis-aligned rectangle, and the result is the smallest bounds that encompasses the visible region.
*/
getBounds(): LngLatBounds {
return this.transform.getBounds();
}
/**
* Returns the maximum geographical bounds the map is constrained to, or `null` if none set.
*/
getMaxBounds(): LngLatBounds | null {
return this.transform.getMaxBounds();
}
/**
* Sets or clears the map's geographical bounds.
*
* Pan and zoom operations are constrained within these bounds.
* If a pan or zoom is performed that would
* display regions outside these bounds, the map will
* instead display a position and zoom level
* as close as possible to the operation's request while still
* remaining within the bounds.
*
* @param {LngLatBoundsLike | null | undefined} bounds The maximum bounds to set. If `null` or `undefined` is provided, the function removes the map's maximum bounds.
* @returns {Map} `this`
*/
setMaxBounds(bounds: LngLatBoundsLike) {
this.transform.setMaxBounds(LngLatBounds.convert(bounds));
return this._update();
}
/**
* Sets or clears the map's minimum zoom level.
* If the map's current zoom level is lower than the new minimum,
* the map will zoom to the new minimum.
*
* @param {number | null | undefined} minZoom The minimum zoom level to set (0-24).
* If `null` or `undefined` is provided, the function removes the current minimum zoom (i.e. sets it to 0).
* @returns {Map} `this`
*/
setMinZoom(minZoom?: ?number) {
minZoom = minZoom === null || minZoom === undefined ? defaultMinZoom : minZoom;
if (minZoom >= defaultMinZoom && minZoom <= this.transform.maxZoom) {
this.transform.minZoom = minZoom;
this._update();
if (this.getZoom() < minZoom) this.setZoom(minZoom);
return this;
} else throw new Error(`minZoom must be between ${defaultMinZoom} and the current maxZoom, inclusive`);
}
/**
* Returns the map's minimum allowable zoom level.
*
* @returns {number} minZoom
*/
getMinZoom() { return this.transform.minZoom; }
/**
* Sets or clears the map's maximum zoom level.
* If the map's current zoom level is higher than the new maximum,
* the map will zoom to the new maximum.
*
* @param {number | null | undefined} maxZoom The maximum zoom level to set.
* If `null` or `undefined` is provided, the function removes the current maximum zoom (sets it to 22).
* @returns {Map} `this`
*/
setMaxZoom(maxZoom?: ?number) {
maxZoom = maxZoom === null || maxZoom === undefined ? defaultMaxZoom : maxZoom;
if (maxZoom >= this.transform.minZoom) {
this.transform.maxZoom = maxZoom;
this._update();
if (this.getZoom() > maxZoom) this.setZoom(maxZoom);
return this;
} else throw new Error(`maxZoom must be greater than the current minZoom`);
}
/**
* Returns the state of renderWorldCopies.
*
* @returns {boolean} renderWorldCopies
*/
getRenderWorldCopies() { return this.transform.renderWorldCopies; }
/**
* Sets the state of renderWorldCopies.
*
* @param {boolean} renderWorldCopies If `true`, multiple copies of the world will be rendered, when zoomed out. `undefined` is treated as `true`, `null` is treated as `false`.
* @returns {Map} `this`
*/
setRenderWorldCopies(renderWorldCopies?: ?boolean) {
this.transform.renderWorldCopies = renderWorldCopies;
return this._update();
}
/**
* Returns the map's maximum allowable zoom level.
*
* @returns {number} maxZoom
*/
getMaxZoom() { return this.transform.maxZoom; }
/**
* Returns a {@link Point} representing pixel coordinates, relative to the map's `container`,
* that correspond to the specified geographical location.
*
* @param {LngLatLike} lnglat The geographical location to project.
* @returns {Point} The {@link Point} corresponding to `lnglat`, relative to the map's `container`.
*/
project(lnglat: LngLatLike) {
return this.transform.locationPoint(LngLat.convert(lnglat));
}
/**
* Returns a {@link LngLat} representing geographical coordinates that correspond
* to the specified pixel coordinates.
*
* @param {PointLike} point The pixel coordinates to unproject.
* @returns {LngLat} The {@link LngLat} corresponding to `point`.
* @see [Show polygon information on click](https://www.mapbox.com/mapbox-gl-js/example/polygon-popup-on-click/)
*/
unproject(point: PointLike) {
return this.transform.pointLocation(Point.convert(point));
}
/**
* Returns true if the map is panning, zooming, rotating, or pitching due to a camera animation or user gesture.
*/
isMoving(): boolean {
return this._moving ||
this.dragPan.isActive() ||
this.dragRotate.isActive() ||
this.scrollZoom.isActive();
}
/**
* Returns true if the map is zooming due to a camera animation or user gesture.
*/
isZooming(): boolean {
return this._zooming ||
this.scrollZoom.isActive();
}
/**
* Returns true if the map is rotating due to a camera animation or user gesture.
*/
isRotating(): boolean {
return this._rotating ||
this.dragRotate.isActive();
}
/**
* Adds a listener for events of a specified type.
*
* @method
* @name on
* @memberof Map
* @instance
* @param {string} type The event type to add a listen for.
* @param {Function} listener The function to be called when the event is fired.
* The listener function is called with the data object passed to `fire`,
* extended with `target` and `type` properties.
* @returns {Map} `this`
*/
/**
* Adds a listener for events of a specified type occurring on features in a specified style layer.
*
* @param {string} type The event type to listen for; one of `'mousedown'`, `'mouseup'`, `'click'`, `'dblclick'`,
* `'mousemove'`, `'mouseenter'`, `'mouseleave'`, `'mouseover'`, `'mouseout'`, `'contextmenu'`, `'touchstart'`,
* `'touchend'`, or `'touchcancel'`. `mouseenter` and `mouseover` events are triggered when the cursor enters
* a visible portion of the specified layer from outside that layer or outside the map canvas. `mouseleave`
* and `mouseout` events are triggered when the cursor leaves a visible portion of the specified layer, or leaves
* the map canvas.
* @param {string} layer The ID of a style layer. Only events whose location is within a visible
* feature in this layer will trigger the listener. The event will have a `features` property containing
* an array of the matching features.
* @param {Function} listener The function to be called when the event is fired.
* @returns {Map} `this`
*/
on(type: MapEvent, layer: any, listener: any) {
if (listener === undefined) {
return super.on(type, layer);
}
const delegatedListener = (() => {
if (type === 'mouseenter' || type === 'mouseover') {
let mousein = false;
const mousemove = (e) => {
const features = this.getLayer(layer) ? this.queryRenderedFeatures(e.point, {layers: [layer]}) : [];
if (!features.length) {
mousein = false;
} else if (!mousein) {
mousein = true;
listener.call(this, new MapMouseEvent(type, this, e.originalEvent, {features}));
}
};
const mouseout = () => {
mousein = false;
};
return {layer, listener, delegates: {mousemove, mouseout}};
} else if (type === 'mouseleave' || type === 'mouseout') {
let mousein = false;
const mousemove = (e) => {
const features = this.getLayer(layer) ? this.queryRenderedFeatures(e.point, {layers: [layer]}) : [];
if (features.length) {
mousein = true;
} else if (mousein) {
mousein = false;
listener.call(this, new MapMouseEvent(type, this, e.originalEvent));
}
};
const mouseout = (e) => {
if (mousein) {
mousein = false;
listener.call(this, new MapMouseEvent(type, this, e.originalEvent));
}
};
return {layer, listener, delegates: {mousemove, mouseout}};
} else {
const delegate = (e) => {
const features = this.getLayer(layer) ? this.queryRenderedFeatures(e.point, {layers: [layer]}) : [];
if (features.length) {
// Here we need to mutate the original event, so that preventDefault works as expected.
e.features = features;
listener.call(this, e);
delete e.features;
}
};
return {layer, listener, delegates: {[type]: delegate}};
}
})();
this._delegatedListeners = this._delegatedListeners || {};
this._delegatedListeners[type] = this._delegatedListeners[type] || [];
this._delegatedListeners[type].push(delegatedListener);
for (const event in delegatedListener.delegates) {
this.on((event: any), delegatedListener.delegates[event]);
}
return this;
}
/**
* Removes an event listener previously added with `Map#on`.
*
* @method
* @name off
* @memberof Map
* @instance
* @param {string} type The event type previously used to install the listener.
* @param {Function} listener The function previously installed as a listener.
* @returns {Map} `this`
*/
/**
* Removes an event listener for layer-specific events previously added with `Map#on`.
*
* @param {string} type The event type previously used to install the listener.
* @param {string} layer The layer ID previously used to install the listener.
* @param {Function} listener The function previously installed as a listener.
* @returns {Map} `this`
*/
off(type: MapEvent, layer: any, listener: any) {
if (listener === undefined) {
return super.off(type, layer);
}
if (this._delegatedListeners && this._delegatedListeners[type]) {
const listeners = this._delegatedListeners[type];
for (let i = 0; i < listeners.length; i++) {
const delegatedListener = listeners[i];
if (delegatedListener.layer === layer && delegatedListener.listener === listener) {
for (const event in delegatedListener.delegates) {
this.off((event: any), delegatedListener.delegates[event]);
}
listeners.splice(i, 1);
return this;
}
}
}
return this;
}
/**
* Returns an array of [GeoJSON](http://geojson.org/)
* [Feature objects](https://tools.ietf.org/html/rfc7946#section-3.2)
* representing visible features that satisfy the query parameters.
*
* @param {PointLike|Array<PointLike>} [geometry] - The geometry of the query region:
* either a single point or southwest and northeast points describing a bounding box.
* Omitting this parameter (i.e. calling {@link Map#queryRenderedFeatures} with zero arguments,
* or with only a `options` argument) is equivalent to passing a bounding box encompassing the entire
* map viewport.
* @param {Object} [options]
* @param {Array<string>} [options.layers] An array of style layer IDs for the query to inspect.
* Only features within these layers will be returned. If this parameter is undefined, all layers will be checked.
* @param {Array} [options.filter] A [filter](https://www.mapbox.com/mapbox-gl-js/style-spec/#other-filter)
* to limit query results.
*
* @returns {Array<Object>} An array of [GeoJSON](http://geojson.org/)
* [feature objects](https://tools.ietf.org/html/rfc7946#section-3.2).
*
* The `properties` value of each returned feature object contains the properties of its source feature. For GeoJSON sources, only
* string and numeric property values are supported (i.e. `null`, `Array`, and `Object` values are not supported).
*
* Each feature includes top-level `layer`, `source`, and `sourceLayer` properties. The `layer` property is an object
* representing the style layer to which the feature belongs. Layout and paint properties in this object contain values
* which are fully evaluated for the given zoom level and feature.
*
* Features from layers whose `visibility` property is `"none"`, or from layers whose zoom range excludes the
* current zoom level are not included. Symbol features that have been hidden due to text or icon collision are
* not included. Features from all other layers are included, including features that may have no visible
* contribution to the rendered result; for example, because the layer's opacity or color alpha component is set to
* 0.
*
* The topmost rendered feature appears first in the returned array, and subsequent features are sorted by
* descending z-order. Features that are rendered multiple times (due to wrapping across the antimeridian at low
* zoom levels) are returned only once (though subject to the following caveat).
*
* Because features come from tiled vector data or GeoJSON data that is converted to tiles internally, feature
* geometries may be split or duplicated across tile boundaries and, as a result, features may appear multiple
* times in query results. For example, suppose there is a highway running through the bounding rectangle of a query.
* The results of the query will be those parts of the highway that lie within the map tiles covering the bounding
* rectangle, even if the highway extends into other tiles, and the portion of the highway within each map tile
* will be returned as a separate feature. Similarly, a point feature near a tile boundary may appear in multiple
* tiles due to tile buffering.
*
* @example
* // Find all features at a point
* var features = map.queryRenderedFeatures(
* [20, 35],
* { layers: ['my-layer-name'] }
* );
*
* @example
* // Find all features within a static bounding box
* var features = map.queryRenderedFeatures(
* [[10, 20], [30, 50]],
* { layers: ['my-layer-name'] }
* );
*
* @example
* // Find all features within a bounding box around a point
* var width = 10;
* var height = 20;
* var features = map.queryRenderedFeatures([
* [point.x - width / 2, point.y - height / 2],
* [point.x + width / 2, point.y + height / 2]
* ], { layers: ['my-layer-name'] });
*
* @example
* // Query all rendered features from a single layer
* var features = map.queryRenderedFeatures({ layers: ['my-layer-name'] });
* @see [Get features under the mouse pointer](https://www.mapbox.com/mapbox-gl-js/example/queryrenderedfeatures/)
* @see [Highlight features within a bounding box](https://www.mapbox.com/mapbox-gl-js/example/using-box-queryrenderedfeatures/)
* @see [Center the map on a clicked symbol](https://www.mapbox.com/mapbox-gl-js/example/center-on-symbol/)
*/
queryRenderedFeatures(geometry?: PointLike | [PointLike, PointLike], options?: Object) {
// The first parameter can be omitted entirely, making this effectively an overloaded method
// with two signatures:
//
// queryRenderedFeatures(geometry: PointLike | [PointLike, PointLike], options?: Object)
// queryRenderedFeatures(options?: Object)
//
// There no way to express that in a way that's compatible with both flow and documentation.js.
// Related: https://github.com/facebook/flow/issues/1556
if (!this.style) {
return [];
}
if (options === undefined && geometry !== undefined && !(geometry instanceof Point) && !Array.isArray(geometry)) {
options = (geometry: Object);
geometry = undefined;
}
options = options || {};
geometry = geometry || [[0, 0], [this.transform.width, this.transform.height]];
let queryGeometry;
if (geometry instanceof Point || typeof geometry[0] === 'number') {
queryGeometry = [Point.convert(geometry)];
} else {
const tl = Point.convert(geometry[0]);
const br = Point.convert(geometry[1]);
queryGeometry = [tl, new Point(br.x, tl.y), br, new Point(tl.x, br.y), tl];
}
return this.style.queryRenderedFeatures(queryGeometry, options, this.transform);
}
/**
* Returns an array of [GeoJSON](http://geojson.org/)
* [Feature objects](https://tools.ietf.org/html/rfc7946#section-3.2)
* representing features within the specified vector tile or GeoJSON source that satisfy the query parameters.
*
* @param {string} sourceID The ID of the vector tile or GeoJSON source to query.
* @param {Object} [parameters]
* @param {string} [parameters.sourceLayer] The name of the vector tile layer to query. *For vector tile
* sources, this parameter is required.* For GeoJSON sources, it is ignored.
* @param {Array} [parameters.filter] A [filter](https://www.mapbox.com/mapbox-gl-js/style-spec/#other-filter)
* to limit query results.
*
* @returns {Array<Object>} An array of [GeoJSON](http://geojson.org/)
* [Feature objects](https://tools.ietf.org/html/rfc7946#section-3.2).
*
* In contrast to {@link Map#queryRenderedFeatures}, this function
* returns all features matching the query parameters,
* whether or not they are rendered by the current style (i.e. visible). The domain of the query includes all currently-loaded
* vector tiles and GeoJSON source tiles: this function does not check tiles outside the currently
* visible viewport.
*
* Because features come from tiled vector data or GeoJSON data that is converted to tiles internally, feature
* geometries may be split or duplicated across tile boundaries and, as a result, features may appear multiple
* times in query results. For example, suppose there is a highway running through the bounding rectangle of a query.
* The results of the query will be those parts of the highway that lie within the map tiles covering the bounding
* rectangle, even if the highway extends into other tiles, and the portion of the highway within each map tile
* will be returned as a separate feature. Similarly, a point feature near a tile boundary may appear in multiple
* tiles due to tile buffering.
* @see [Filter features within map view](https://www.mapbox.com/mapbox-gl-js/example/filter-features-within-map-view/)
* @see [Highlight features containing similar data](https://www.mapbox.com/mapbox-gl-js/example/query-similar-features/)
*/
querySourceFeatures(sourceID: string, parameters: ?{sourceLayer: ?string, filter: ?Array<any>}) {
return this.style.querySourceFeatures(sourceID, parameters);
}
/**
* Updates the map's Mapbox style object with a new value. If the given
* value is style JSON object, compares it against the the map's current
* state and perform only the changes necessary to make the map style match
* the desired state.
*
* @param style A JSON object conforming to the schema described in the
* [Mapbox Style Specification](https://mapbox.com/mapbox-gl-style-spec/), or a URL to such JSON.
* @param {Object} [options]
* @param {boolean} [options.diff=true] If false, force a 'full' update, removing the current style
* and adding building the given one instead of attempting a diff-based update.
* @param {string} [options.localIdeographFontFamily=null] If non-null, defines a css font-family
* for locally overriding generation of glyphs in the 'CJK Unified Ideographs' and 'Hangul Syllables'
* ranges. Forces a full update.
* @returns {Map} `this`
* @see [Change a map's style](https://www.mapbox.com/mapbox-gl-js/example/setstyle/)
*/
setStyle(style: StyleSpecification | string | null, options?: {diff?: boolean} & StyleOptions) {
const shouldTryDiff = (!options || (options.diff !== false && !options.localIdeographFontFamily)) && this.style;
if (shouldTryDiff && style && typeof style === 'object') {
try {
if (this.style.setState(style)) {
this._update(true);
}
return this;
} catch (e) {
warnOnce(
`Unable to perform style diff: ${e.message || e.error || e}. Rebuilding the style from scratch.`
);
}
}
if (this.style) {
this.style.setEventedParent(null);
this.style._remove();
}
if (!style) {
delete this.style;
return this;
} else {
this.style = new Style(this, options || {});
}
this.style.setEventedParent(this, {style: this.style});
if (typeof style === 'string') {
this.style.loadURL(style);
} else {
this.style.loadJSON(style);
}
return this;
}
/**
* Returns the map's Mapbox style object, which can be used to recreate the map's style.
*
* @returns {Object} The map's style object.
*/
getStyle() {
if (this.style) {
return this.style.serialize();
}
}