-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
style.js
1268 lines (1055 loc) · 43.8 KB
/
style.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 assert from 'assert';
import { Event, ErrorEvent, Evented } from '../util/evented';
import StyleLayer from './style_layer';
import createStyleLayer from './create_style_layer';
import loadSprite from './load_sprite';
import ImageManager from '../render/image_manager';
import GlyphManager from '../render/glyph_manager';
import Light from './light';
import LineAtlas from '../render/line_atlas';
import { pick, clone, extend, deepEqual, filterObject, mapObject } from '../util/util';
import { getJSON, getReferrer, makeRequest, ResourceType } from '../util/ajax';
import { isMapboxURL, normalizeStyleURL } from '../util/mapbox';
import browser from '../util/browser';
import Dispatcher from '../util/dispatcher';
import { validateStyle, emitValidationErrors as _emitValidationErrors } from './validate_style';
import {
getType as getSourceType,
setType as setSourceType,
type SourceClass
} from '../source/source';
import { queryRenderedFeatures, queryRenderedSymbols, querySourceFeatures } from '../source/query_features';
import SourceCache from '../source/source_cache';
import GeoJSONSource from '../source/geojson_source';
import styleSpec from '../style-spec/reference/latest';
import getWorkerPool from '../util/global_worker_pool';
import deref from '../style-spec/deref';
import diffStyles, {operations as diffOperations} from '../style-spec/diff';
import {
registerForPluginAvailability,
evented as rtlTextPluginEvented
} from '../source/rtl_text_plugin';
import PauseablePlacement from './pauseable_placement';
import ZoomHistory from './zoom_history';
import CrossTileSymbolIndex from '../symbol/cross_tile_symbol_index';
import {validateCustomStyleLayer} from './style_layer/custom_style_layer';
// We're skipping validation errors with the `source.canvas` identifier in order
// to continue to allow canvas sources to be added at runtime/updated in
// smart setStyle (see https://github.com/mapbox/mapbox-gl-js/pull/6424):
const emitValidationErrors = (evented: Evented, errors: ?$ReadOnlyArray<{message: string, identifier?: string}>) =>
_emitValidationErrors(evented, errors && errors.filter(error => error.identifier !== 'source.canvas'));
import type Map from '../ui/map';
import type Transform from '../geo/transform';
import type {StyleImage} from './style_image';
import type {StyleGlyph} from './style_glyph';
import type {Callback} from '../types/callback';
import type EvaluationParameters from './evaluation_parameters';
import type {Placement} from '../symbol/placement';
import type {Cancelable} from '../types/cancelable';
import type {RequestParameters, ResponseCallback} from '../util/ajax';
import type {GeoJSON} from '@mapbox/geojson-types';
import type {
LayerSpecification,
FilterSpecification,
StyleSpecification,
LightSpecification,
SourceSpecification
} from '../style-spec/types';
import type {CustomLayerInterface} from './style_layer/custom_style_layer';
const supportedDiffOperations = pick(diffOperations, [
'addLayer',
'removeLayer',
'setPaintProperty',
'setLayoutProperty',
'setFilter',
'addSource',
'removeSource',
'setLayerZoomRange',
'setLight',
'setTransition',
'setGeoJSONSourceData'
// 'setGlyphs',
// 'setSprite',
]);
const ignoredDiffOperations = pick(diffOperations, [
'setCenter',
'setZoom',
'setBearing',
'setPitch'
]);
export type StyleOptions = {
validate?: boolean,
localIdeographFontFamily?: string
};
export type StyleSetterOptions = {
validate?: boolean
};
/**
* @private
*/
class Style extends Evented {
map: Map;
stylesheet: StyleSpecification;
dispatcher: Dispatcher;
imageManager: ImageManager;
glyphManager: GlyphManager;
lineAtlas: LineAtlas;
light: Light;
_request: ?Cancelable;
_spriteRequest: ?Cancelable;
_layers: {[string]: StyleLayer};
_order: Array<string>;
sourceCaches: {[string]: SourceCache};
zoomHistory: ZoomHistory;
_loaded: boolean;
_rtlTextPluginCallback: Function;
_changed: boolean;
_updatedSources: {[string]: 'clear' | 'reload'};
_updatedLayers: {[string]: true};
_removedLayers: {[string]: StyleLayer};
_updatedPaintProps: {[layer: string]: true};
_layerOrderChanged: boolean;
crossTileSymbolIndex: CrossTileSymbolIndex;
pauseablePlacement: PauseablePlacement;
placement: Placement;
z: number;
// exposed to allow stubbing by unit tests
static getSourceType: typeof getSourceType;
static setSourceType: typeof setSourceType;
static registerForPluginAvailability: typeof registerForPluginAvailability;
constructor(map: Map, options: StyleOptions = {}) {
super();
this.map = map;
this.dispatcher = new Dispatcher(getWorkerPool(), this);
this.imageManager = new ImageManager();
this.imageManager.setEventedParent(this);
this.glyphManager = new GlyphManager(map._transformRequest, options.localIdeographFontFamily);
this.lineAtlas = new LineAtlas(256, 512);
this.crossTileSymbolIndex = new CrossTileSymbolIndex();
this._layers = {};
this._order = [];
this.sourceCaches = {};
this.zoomHistory = new ZoomHistory();
this._loaded = false;
this._resetUpdates();
this.dispatcher.broadcast('setReferrer', getReferrer());
const self = this;
this._rtlTextPluginCallback = Style.registerForPluginAvailability((args) => {
self.dispatcher.broadcast('loadRTLTextPlugin', args.pluginURL, args.completionCallback);
for (const id in self.sourceCaches) {
self.sourceCaches[id].reload(); // Should be a no-op if the plugin loads before any tiles load
}
});
this.on('data', (event) => {
if (event.dataType !== 'source' || event.sourceDataType !== 'metadata') {
return;
}
const sourceCache = this.sourceCaches[event.sourceId];
if (!sourceCache) {
return;
}
const source = sourceCache.getSource();
if (!source || !source.vectorLayerIds) {
return;
}
for (const layerId in this._layers) {
const layer = this._layers[layerId];
if (layer.source === source.id) {
this._validateLayer(layer);
}
}
});
}
loadURL(url: string, options: {
validate?: boolean,
accessToken?: string
} = {}) {
this.fire(new Event('dataloading', {dataType: 'style'}));
const validate = typeof options.validate === 'boolean' ?
options.validate : !isMapboxURL(url);
url = normalizeStyleURL(url, options.accessToken);
const request = this.map._transformRequest(url, ResourceType.Style);
this._request = getJSON(request, (error: ?Error, json: ?Object) => {
this._request = null;
if (error) {
this.fire(new ErrorEvent(error));
} else if (json) {
this._load(json, validate);
}
});
}
loadJSON(json: StyleSpecification, options: StyleSetterOptions = {}) {
this.fire(new Event('dataloading', {dataType: 'style'}));
this._request = browser.frame(() => {
this._request = null;
this._load(json, options.validate !== false);
});
}
_load(json: StyleSpecification, validate: boolean) {
if (validate && emitValidationErrors(this, validateStyle(json))) {
return;
}
this._loaded = true;
this.stylesheet = json;
for (const id in json.sources) {
this.addSource(id, json.sources[id], {validate: false});
}
if (json.sprite) {
this._spriteRequest = loadSprite(json.sprite, this.map._transformRequest, (err, images) => {
this._spriteRequest = null;
if (err) {
this.fire(new ErrorEvent(err));
} else if (images) {
for (const id in images) {
this.imageManager.addImage(id, images[id]);
}
}
this.imageManager.setLoaded(true);
this.fire(new Event('data', {dataType: 'style'}));
});
} else {
this.imageManager.setLoaded(true);
}
this.glyphManager.setURL(json.glyphs);
const layers = deref(this.stylesheet.layers);
this._order = layers.map((layer) => layer.id);
this._layers = {};
for (let layer of layers) {
layer = createStyleLayer(layer);
layer.setEventedParent(this, {layer: {id: layer.id}});
this._layers[layer.id] = layer;
}
this.dispatcher.broadcast('setLayers', this._serializeLayers(this._order));
this.light = new Light(this.stylesheet.light);
this.fire(new Event('data', {dataType: 'style'}));
this.fire(new Event('style.load'));
}
_validateLayer(layer: StyleLayer) {
const sourceCache = this.sourceCaches[layer.source];
if (!sourceCache) {
return;
}
const sourceLayer = layer.sourceLayer;
if (!sourceLayer) {
return;
}
const source = sourceCache.getSource();
if (source.type === 'geojson' || (source.vectorLayerIds && source.vectorLayerIds.indexOf(sourceLayer) === -1)) {
this.fire(new ErrorEvent(new Error(
`Source layer "${sourceLayer}" ` +
`does not exist on source "${source.id}" ` +
`as specified by style layer "${layer.id}"`
)));
}
}
loaded() {
if (!this._loaded)
return false;
if (Object.keys(this._updatedSources).length)
return false;
for (const id in this.sourceCaches)
if (!this.sourceCaches[id].loaded())
return false;
if (!this.imageManager.isLoaded())
return false;
return true;
}
_serializeLayers(ids: Array<string>): Array<Object> {
const serializedLayers = [];
for (const id of ids) {
const layer = this._layers[id];
if (layer.type !== 'custom') {
serializedLayers.push(layer.serialize());
}
}
return serializedLayers;
}
hasTransitions() {
if (this.light && this.light.hasTransition()) {
return true;
}
for (const id in this.sourceCaches) {
if (this.sourceCaches[id].hasTransition()) {
return true;
}
}
for (const id in this._layers) {
if (this._layers[id].hasTransition()) {
return true;
}
}
return false;
}
_checkLoaded() {
if (!this._loaded) {
throw new Error('Style is not done loading');
}
}
/**
* Apply queued style updates in a batch and recalculate zoom-dependent paint properties.
*/
update(parameters: EvaluationParameters) {
if (!this._loaded) {
return;
}
const changed = this._changed;
if (this._changed) {
const updatedIds = Object.keys(this._updatedLayers);
const removedIds = Object.keys(this._removedLayers);
if (updatedIds.length || removedIds.length) {
this._updateWorkerLayers(updatedIds, removedIds);
}
for (const id in this._updatedSources) {
const action = this._updatedSources[id];
assert(action === 'reload' || action === 'clear');
if (action === 'reload') {
this._reloadSource(id);
} else if (action === 'clear') {
this._clearSource(id);
}
}
for (const id in this._updatedPaintProps) {
this._layers[id].updateTransitions(parameters);
}
this.light.updateTransitions(parameters);
this._resetUpdates();
}
for (const sourceId in this.sourceCaches) {
this.sourceCaches[sourceId].used = false;
}
for (const layerId of this._order) {
const layer = this._layers[layerId];
layer.recalculate(parameters);
if (!layer.isHidden(parameters.zoom) && layer.source) {
this.sourceCaches[layer.source].used = true;
}
}
this.light.recalculate(parameters);
this.z = parameters.zoom;
if (changed) {
this.fire(new Event('data', {dataType: 'style'}));
}
}
_updateWorkerLayers(updatedIds: Array<string>, removedIds: Array<string>) {
this.dispatcher.broadcast('updateLayers', {
layers: this._serializeLayers(updatedIds),
removedIds
});
}
_resetUpdates() {
this._changed = false;
this._updatedLayers = {};
this._removedLayers = {};
this._updatedSources = {};
this._updatedPaintProps = {};
}
/**
* Update this style's state to match the given style JSON, performing only
* the necessary mutations.
*
* May throw an Error ('Unimplemented: METHOD') if the mapbox-gl-style-spec
* diff algorithm produces an operation that is not supported.
*
* @returns {boolean} true if any changes were made; false otherwise
* @private
*/
setState(nextState: StyleSpecification) {
this._checkLoaded();
if (emitValidationErrors(this, validateStyle(nextState))) return false;
nextState = clone(nextState);
nextState.layers = deref(nextState.layers);
const changes = diffStyles(this.serialize(), nextState)
.filter(op => !(op.command in ignoredDiffOperations));
if (changes.length === 0) {
return false;
}
const unimplementedOps = changes.filter(op => !(op.command in supportedDiffOperations));
if (unimplementedOps.length > 0) {
throw new Error(`Unimplemented: ${unimplementedOps.map(op => op.command).join(', ')}.`);
}
changes.forEach((op) => {
if (op.command === 'setTransition') {
// `transition` is always read directly off of
// `this.stylesheet`, which we update below
return;
}
(this: any)[op.command].apply(this, op.args);
});
this.stylesheet = nextState;
return true;
}
addImage(id: string, image: StyleImage) {
if (this.getImage(id)) {
return this.fire(new ErrorEvent(new Error('An image with this name already exists.')));
}
this.imageManager.addImage(id, image);
this.fire(new Event('data', {dataType: 'style'}));
}
updateImage(id: string, image: StyleImage) {
this.imageManager.updateImage(id, image);
}
getImage(id: string): ?StyleImage {
return this.imageManager.getImage(id);
}
removeImage(id: string) {
if (!this.getImage(id)) {
return this.fire(new ErrorEvent(new Error('No image with this name exists.')));
}
this.imageManager.removeImage(id);
this.fire(new Event('data', {dataType: 'style'}));
}
listImages() {
this._checkLoaded();
return this.imageManager.listImages();
}
addSource(id: string, source: SourceSpecification, options: StyleSetterOptions = {}) {
this._checkLoaded();
if (this.sourceCaches[id] !== undefined) {
throw new Error('There is already a source with this ID');
}
if (!source.type) {
throw new Error(`The type property must be defined, but the only the following properties were given: ${Object.keys(source).join(', ')}.`);
}
const builtIns = ['vector', 'raster', 'geojson', 'video', 'image'];
const shouldValidate = builtIns.indexOf(source.type) >= 0;
if (shouldValidate && this._validate(validateStyle.source, `sources.${id}`, source, null, options)) return;
if (this.map && this.map._collectResourceTiming) (source: any).collectResourceTiming = true;
const sourceCache = this.sourceCaches[id] = new SourceCache(id, source, this.dispatcher);
sourceCache.style = this;
sourceCache.setEventedParent(this, () => ({
isSourceLoaded: this.loaded(),
source: sourceCache.serialize(),
sourceId: id
}));
sourceCache.onAdd(this.map);
this._changed = true;
}
/**
* Remove a source from this stylesheet, given its id.
* @param {string} id id of the source to remove
* @throws {Error} if no source is found with the given ID
*/
removeSource(id: string) {
this._checkLoaded();
if (this.sourceCaches[id] === undefined) {
throw new Error('There is no source with this ID');
}
for (const layerId in this._layers) {
if (this._layers[layerId].source === id) {
return this.fire(new ErrorEvent(new Error(`Source "${id}" cannot be removed while layer "${layerId}" is using it.`)));
}
}
const sourceCache = this.sourceCaches[id];
delete this.sourceCaches[id];
delete this._updatedSources[id];
sourceCache.fire(new Event('data', {sourceDataType: 'metadata', dataType:'source', sourceId: id}));
sourceCache.setEventedParent(null);
sourceCache.clearTiles();
if (sourceCache.onRemove) sourceCache.onRemove(this.map);
this._changed = true;
}
/**
* Set the data of a GeoJSON source, given its id.
* @param {string} id id of the source
* @param {GeoJSON|string} data GeoJSON source
*/
setGeoJSONSourceData(id: string, data: GeoJSON | string) {
this._checkLoaded();
assert(this.sourceCaches[id] !== undefined, 'There is no source with this ID');
const geojsonSource: GeoJSONSource = (this.sourceCaches[id].getSource(): any);
assert(geojsonSource.type === 'geojson');
geojsonSource.setData(data);
this._changed = true;
}
/**
* Get a source by id.
* @param {string} id id of the desired source
* @returns {Object} source
*/
getSource(id: string): Object {
return this.sourceCaches[id] && this.sourceCaches[id].getSource();
}
/**
* Add a layer to the map style. The layer will be inserted before the layer with
* ID `before`, or appended if `before` is omitted.
* @param {string} [before] ID of an existing layer to insert before
*/
addLayer(layerObject: LayerSpecification | CustomLayerInterface, before?: string, options: StyleSetterOptions = {}) {
this._checkLoaded();
const id = layerObject.id;
if (this.getLayer(id)) {
this.fire(new ErrorEvent(new Error(`Layer with id "${id}" already exists on this map`)));
return;
}
let layer;
if (layerObject.type === 'custom') {
if (emitValidationErrors(this, validateCustomStyleLayer(layerObject))) return;
layer = createStyleLayer(layerObject);
} else {
if (typeof layerObject.source === 'object') {
this.addSource(id, layerObject.source);
layerObject = clone(layerObject);
layerObject = (extend(layerObject, {source: id}): any);
}
// this layer is not in the style.layers array, so we pass an impossible array index
if (this._validate(validateStyle.layer,
`layers.${id}`, layerObject, {arrayIndex: -1}, options)) return;
layer = createStyleLayer(layerObject);
this._validateLayer(layer);
layer.setEventedParent(this, {layer: {id}});
}
const index = before ? this._order.indexOf(before) : this._order.length;
if (before && index === -1) {
this.fire(new ErrorEvent(new Error(`Layer with id "${before}" does not exist on this map.`)));
return;
}
this._order.splice(index, 0, id);
this._layerOrderChanged = true;
this._layers[id] = layer;
if (this._removedLayers[id] && layer.source && layer.type !== 'custom') {
// If, in the current batch, we have already removed this layer
// and we are now re-adding it with a different `type`, then we
// need to clear (rather than just reload) the underyling source's
// tiles. Otherwise, tiles marked 'reloading' will have buckets /
// buffers that are set up for the _previous_ version of this
// layer, causing, e.g.:
// https://github.com/mapbox/mapbox-gl-js/issues/3633
const removed = this._removedLayers[id];
delete this._removedLayers[id];
if (removed.type !== layer.type) {
this._updatedSources[layer.source] = 'clear';
} else {
this._updatedSources[layer.source] = 'reload';
this.sourceCaches[layer.source].pause();
}
}
this._updateLayer(layer);
if (layer.onAdd) {
layer.onAdd(this.map);
}
}
/**
* Moves a layer to a different z-position. The layer will be inserted before the layer with
* ID `before`, or appended if `before` is omitted.
* @param {string} id ID of the layer to move
* @param {string} [before] ID of an existing layer to insert before
*/
moveLayer(id: string, before?: string) {
this._checkLoaded();
this._changed = true;
const layer = this._layers[id];
if (!layer) {
this.fire(new ErrorEvent(new Error(`The layer '${id}' does not exist in the map's style and cannot be moved.`)));
return;
}
if (id === before) {
return;
}
const index = this._order.indexOf(id);
this._order.splice(index, 1);
const newIndex = before ? this._order.indexOf(before) : this._order.length;
if (before && newIndex === -1) {
this.fire(new ErrorEvent(new Error(`Layer with id "${before}" does not exist on this map.`)));
return;
}
this._order.splice(newIndex, 0, id);
this._layerOrderChanged = true;
}
/**
* Remove the layer with the given id from the style.
*
* If no such layer exists, an `error` event is fired.
*
* @param {string} id id of the layer to remove
* @fires error
*/
removeLayer(id: string) {
this._checkLoaded();
const layer = this._layers[id];
if (!layer) {
this.fire(new ErrorEvent(new Error(`The layer '${id}' does not exist in the map's style and cannot be removed.`)));
return;
}
layer.setEventedParent(null);
const index = this._order.indexOf(id);
this._order.splice(index, 1);
this._layerOrderChanged = true;
this._changed = true;
this._removedLayers[id] = layer;
delete this._layers[id];
delete this._updatedLayers[id];
delete this._updatedPaintProps[id];
if (layer.onRemove) {
layer.onRemove(this.map);
}
}
/**
* Return the style layer object with the given `id`.
*
* @param {string} id - id of the desired layer
* @returns {?Object} a layer, if one with the given `id` exists
*/
getLayer(id: string): Object {
return this._layers[id];
}
setLayerZoomRange(layerId: string, minzoom: ?number, maxzoom: ?number) {
this._checkLoaded();
const layer = this.getLayer(layerId);
if (!layer) {
this.fire(new ErrorEvent(new Error(`The layer '${layerId}' does not exist in the map's style and cannot have zoom extent.`)));
return;
}
if (layer.minzoom === minzoom && layer.maxzoom === maxzoom) return;
if (minzoom != null) {
layer.minzoom = minzoom;
}
if (maxzoom != null) {
layer.maxzoom = maxzoom;
}
this._updateLayer(layer);
}
setFilter(layerId: string, filter: ?FilterSpecification, options: StyleSetterOptions = {}) {
this._checkLoaded();
const layer = this.getLayer(layerId);
if (!layer) {
this.fire(new ErrorEvent(new Error(`The layer '${layerId}' does not exist in the map's style and cannot be filtered.`)));
return;
}
if (deepEqual(layer.filter, filter)) {
return;
}
if (filter === null || filter === undefined) {
layer.filter = undefined;
this._updateLayer(layer);
return;
}
if (this._validate(validateStyle.filter, `layers.${layer.id}.filter`, filter, null, options)) {
return;
}
layer.filter = clone(filter);
this._updateLayer(layer);
}
/**
* Get a layer's filter object
* @param {string} layer the layer to inspect
* @returns {*} the layer's filter, if any
*/
getFilter(layer: string) {
return clone(this.getLayer(layer).filter);
}
setLayoutProperty(layerId: string, name: string, value: any, options: StyleSetterOptions = {}) {
this._checkLoaded();
const layer = this.getLayer(layerId);
if (!layer) {
this.fire(new ErrorEvent(new Error(`The layer '${layerId}' does not exist in the map's style and cannot be styled.`)));
return;
}
if (deepEqual(layer.getLayoutProperty(name), value)) return;
layer.setLayoutProperty(name, value, options);
this._updateLayer(layer);
}
/**
* Get a layout property's value from a given layer
* @param {string} layerId the layer to inspect
* @param {string} name the name of the layout property
* @returns {*} the property value
*/
getLayoutProperty(layerId: string, name: string) {
const layer = this.getLayer(layerId);
if (!layer) {
this.fire(new ErrorEvent(new Error(`The layer '${layerId}' does not exist in the map's style.`)));
return;
}
return layer.getLayoutProperty(name);
}
setPaintProperty(layerId: string, name: string, value: any, options: StyleSetterOptions = {}) {
this._checkLoaded();
const layer = this.getLayer(layerId);
if (!layer) {
this.fire(new ErrorEvent(new Error(`The layer '${layerId}' does not exist in the map's style and cannot be styled.`)));
return;
}
if (deepEqual(layer.getPaintProperty(name), value)) return;
const requiresRelayout = layer.setPaintProperty(name, value, options);
if (requiresRelayout) {
this._updateLayer(layer);
}
this._changed = true;
this._updatedPaintProps[layerId] = true;
}
getPaintProperty(layer: string, name: string) {
return this.getLayer(layer).getPaintProperty(name);
}
setFeatureState(feature: { source: string; sourceLayer?: string; id: string | number; }, state: Object) {
this._checkLoaded();
const sourceId = feature.source;
const sourceLayer = feature.sourceLayer;
const sourceCache = this.sourceCaches[sourceId];
const featureId = parseInt(feature.id, 10);
if (sourceCache === undefined) {
this.fire(new ErrorEvent(new Error(`The source '${sourceId}' does not exist in the map's style.`)));
return;
}
const sourceType = sourceCache.getSource().type;
if (sourceType === 'geojson' && sourceLayer) {
this.fire(new ErrorEvent(new Error(`GeoJSON sources cannot have a sourceLayer parameter.`)));
return;
}
if (sourceType === 'vector' && !sourceLayer) {
this.fire(new ErrorEvent(new Error(`The sourceLayer parameter must be provided for vector source types.`)));
return;
}
if (isNaN(featureId) || featureId < 0) {
this.fire(new ErrorEvent(new Error(`The feature id parameter must be provided and non-negative.`)));
return;
}
sourceCache.setFeatureState(sourceLayer, featureId, state);
}
removeFeatureState(target: { source: string; sourceLayer?: string; id?: string | number; }, key?: string) {
this._checkLoaded();
const sourceId = target.source;
const sourceCache = this.sourceCaches[sourceId];
if (sourceCache === undefined) {
this.fire(new ErrorEvent(new Error(`The source '${sourceId}' does not exist in the map's style.`)));
return;
}
const sourceType = sourceCache.getSource().type;
const sourceLayer = sourceType === 'vector' ? target.sourceLayer : undefined;
const featureId = parseInt(target.id, 10);
if (sourceType === 'vector' && !sourceLayer) {
this.fire(new ErrorEvent(new Error(`The sourceLayer parameter must be provided for vector source types.`)));
return;
}
if (target.id && isNaN(featureId) || featureId < 0) {
this.fire(new ErrorEvent(new Error(`The feature id parameter must be non-negative.`)));
return;
}
if (key && !target.id) {
this.fire(new ErrorEvent(new Error(`A feature id is requred to remove its specific state property.`)));
return;
}
sourceCache.removeFeatureState(sourceLayer, featureId, key);
}
getFeatureState(feature: { source: string; sourceLayer?: string; id: string | number; }) {
this._checkLoaded();
const sourceId = feature.source;
const sourceLayer = feature.sourceLayer;
const sourceCache = this.sourceCaches[sourceId];
const featureId = parseInt(feature.id, 10);
if (sourceCache === undefined) {
this.fire(new ErrorEvent(new Error(`The source '${sourceId}' does not exist in the map's style.`)));
return;
}
const sourceType = sourceCache.getSource().type;
if (sourceType === 'vector' && !sourceLayer) {
this.fire(new ErrorEvent(new Error(`The sourceLayer parameter must be provided for vector source types.`)));
return;
}
if (isNaN(featureId) || featureId < 0) {
this.fire(new ErrorEvent(new Error(`The feature id parameter must be provided and non-negative.`)));
return;
}
return sourceCache.getFeatureState(sourceLayer, featureId);
}
getTransition() {
return extend({ duration: 300, delay: 0 }, this.stylesheet && this.stylesheet.transition);
}
serialize() {
return filterObject({
version: this.stylesheet.version,
name: this.stylesheet.name,
metadata: this.stylesheet.metadata,
light: this.stylesheet.light,
center: this.stylesheet.center,
zoom: this.stylesheet.zoom,
bearing: this.stylesheet.bearing,
pitch: this.stylesheet.pitch,
sprite: this.stylesheet.sprite,
glyphs: this.stylesheet.glyphs,
transition: this.stylesheet.transition,
sources: mapObject(this.sourceCaches, (source) => source.serialize()),
layers: this._serializeLayers(this._order)
}, (value) => { return value !== undefined; });
}
_updateLayer(layer: StyleLayer) {
this._updatedLayers[layer.id] = true;
if (layer.source && !this._updatedSources[layer.source]) {
this._updatedSources[layer.source] = 'reload';
this.sourceCaches[layer.source].pause();
}
this._changed = true;
}
_flattenAndSortRenderedFeatures(sourceResults: Array<any>) {
// Feature order is complicated.
// The order between features in two 2D layers is always determined by layer order.
// The order between features in two 3D layers is always determined by depth.
// The order between a feature in a 2D layer and a 3D layer is tricky:
// Most often layer order determines the feature order in this case. If
// a line layer is above a extrusion layer the line feature will be rendered
// above the extrusion. If the line layer is below the extrusion layer,
// it will be rendered below it.
//
// There is a weird case though.
// You have layers in this order: extrusion_layer_a, line_layer, extrusion_layer_b
// Each layer has a feature that overlaps the other features.
// The feature in extrusion_layer_a is closer than the feature in extrusion_layer_b so it is rendered above.
// The feature in line_layer is rendered above extrusion_layer_a.
// This means that that the line_layer feature is above the extrusion_layer_b feature despite
// it being in an earlier layer.
const isLayer3D = layerId => this._layers[layerId].type === 'fill-extrusion';
const layerIndex = {};
const features3D = [];
for (let l = this._order.length - 1; l >= 0; l--) {
const layerId = this._order[l];
if (isLayer3D(layerId)) {
layerIndex[layerId] = l;
for (const sourceResult of sourceResults) {
const layerFeatures = sourceResult[layerId];
if (layerFeatures) {
for (const featureWrapper of layerFeatures) {
features3D.push(featureWrapper);
}
}
}
}
}
features3D.sort((a, b) => {
return b.intersectionZ - a.intersectionZ;
});
const features = [];
for (let l = this._order.length - 1; l >= 0; l--) {
const layerId = this._order[l];
if (isLayer3D(layerId)) {
// add all 3D features that are in or above the current layer
for (let i = features3D.length - 1; i >= 0; i--) {
const topmost3D = features3D[i].feature;
if (layerIndex[topmost3D.layer.id] < l) break;
features.push(topmost3D);
features3D.pop();