forked from SuperMap/iClient-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebMapV3.js
More file actions
1411 lines (1337 loc) · 43.3 KB
/
WebMapV3.js
File metadata and controls
1411 lines (1337 loc) · 43.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright© 2000 - 2021 SuperMap Software Co.Ltd. All rights reserved.
* This program are made available under the terms of the Apache License, Version 2.0
* which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/
import { FetchRequest } from '../util/FetchRequest';
import { getLayerCatalogRenderLayers, getLayerInfosFromCatalogs, getMainLayerFromCatalog, isSameRasterLayer, mergeFeatures, transformUrl } from './utils/util';
import { SourceListModelV3 } from './utils/SourceListModelV3';
const LEGEND_RENDER_TYPE = {
TEXT: 'TEXT',
POINT: 'POINT',
LINE: 'LINE',
FILL: 'FILL',
FILLEXTRUSION: 'FILLEXTRUSION',
ANIMATEPOINT: 'ANIMATEPOINT',
ANIMATELINE: 'ANIMATELINE',
RADARPOINT: 'RADARPOINT',
BUILTINSYMBOL: 'BUILTINSYMBOL'
};
const LEGEND_SHAPE_TYPE = {
TEXT: 'TEXT',
POINT: 'POINT',
LINE: 'LINE',
RECTANGLE: 'RECTANGLE',
ANIMATEPOINT: 'ANIMATEPOINT',
ANIMATELINE: 'ANIMATELINE',
RADARPOINT: 'RADARPOINT',
HEXAGON: 'HEXAGON',
TRIANGLE: 'TRIANGLE',
LINEGRADIENT: 'LINEGRADIENT'
};
const LEGEND_CSS_STATE_KEY = {
fontSize: 'size',
backgroundColor: 'color'
};
const LEGEND_CSS_DEFAULT = {
[LEGEND_RENDER_TYPE.TEXT]: {
textSize: '16px',
textColor: '#FFFFFF',
textOpacity: 1,
textHaloColor: '#242424',
textHaloBlur: 1,
textHaloWidth: 1,
textFont: 'Microsoft YaHei'
},
[LEGEND_RENDER_TYPE.POINT]: {
fontSize: '8px',
color: '#FFFFFF',
opacity: 1
},
[LEGEND_RENDER_TYPE.BUILTINSYMBOL]: {
fontSize: '12px',
color: '#FFFFFF',
opacity: 1
},
[LEGEND_RENDER_TYPE.LINE]: {
width: 20,
height: 8,
backgroundColor: '#FFFFFF',
opacity: 1
},
[LEGEND_RENDER_TYPE.FILL]: {
width: '20px',
height: '20px',
opacity: 1,
backgroundColor: '#FFFFFF',
marginLeft: '1px',
outline: '1px solid transparent',
outlineColor: '#FFFFFF'
},
[LEGEND_RENDER_TYPE.FILLEXTRUSION]: {
width: '20px',
height: '20px',
opacity: 1,
backgroundColor: '#FFFFFF'
},
[LEGEND_RENDER_TYPE.ANIMATEPOINT]: {
size: 30, // UI 上显示直径
color: '#EE4D5A',
opacity: 0.9,
speed: 1,
rings: 3
},
[LEGEND_RENDER_TYPE.ANIMATELINE]: {
width: 20,
height: 8,
backgroundColor: '#FFFFFF',
opacity: 1
},
[LEGEND_RENDER_TYPE.RADARPOINT]: {
size: 60, // UI 上显示直径
color: '#EE4D5A',
opacity: 0.9,
speed: 3
}
};
const LegendTextDataDrivenStyleKey = [
'textSize',
'textColor',
'textOpacity',
'textHaloColor'
];
const LEGEND_STYLE_KEYS = {
[LEGEND_RENDER_TYPE.TEXT]: [...LegendTextDataDrivenStyleKey, 'symbolsContent', 'textField', 'textFont', 'textHaloBlur', 'textHaloWidth'],
[LEGEND_RENDER_TYPE.POINT]: ['symbolsContent', 'size', 'color', 'opacity'],
[LEGEND_RENDER_TYPE.BUILTINSYMBOL]: ['symbolsContent', 'size', 'color', 'opacity'],
[LEGEND_RENDER_TYPE.LINE]: ['width', 'color', 'opacity', 'lineDasharray', 'symbolsContent'],
[LEGEND_RENDER_TYPE.FILL]: ['color', 'opacity', 'antialias', 'outlineColor', 'symbolsContent'],
[LEGEND_RENDER_TYPE.FILLEXTRUSION]: ['color', 'opacity', 'symbolsContent'],
[LEGEND_RENDER_TYPE.ANIMATEPOINT]: ['color', 'opacity', 'size', 'speed', 'rings'],
[LEGEND_RENDER_TYPE.ANIMATELINE]: ['color', 'opacity', 'width', 'textureBlend', 'symbolsContent', 'iconStep'],
[LEGEND_RENDER_TYPE.RADARPOINT]: ['color', 'opacity', 'size', 'speed']
};
const LEGEND_SYMBOL_DEFAULT = {
[LEGEND_RENDER_TYPE.POINT]: 'circle',
[LEGEND_RENDER_TYPE.BUILTINSYMBOL]: 'circle',
[LEGEND_RENDER_TYPE.FILL]: 'polygon-0',
[LEGEND_RENDER_TYPE.FILLEXTRUSION]: 'polygon-0'
};
const LegendType = {
LINEAR: 'LINEAR',
UNIQUE: 'UNIQUE',
RANGE: 'RANGE'
};
const SymbolType = {
line: 'line',
point: 'point',
polygon: 'polygon'
};
const MAP_LAYER_TYPE_2_SYMBOL_TYPE = {
circle: 'point',
line: 'line',
symbol: 'point',
fill: 'polygon',
'fill-extrusion': 'polygon',
heatmap: 'point',
// background: 'background',//无此符号类型
// L7
radar: 'point',
'point-extrusion': 'point',
'heatmap-extrusion': 'point',
'line-extrusion': 'line',
'line-curve': 'line',
'line-curve-extrusion': 'line'
};
const LEGEND_LINE_WIDTH = 100;
const LINE_WIDTH_KEY = 'line-width';
export const LEGEND_STYLE_TYPES = {
IMAGE: 'image',
STYLE: 'style'
};
export function createWebMapV3Extending(SuperClass, { MapManager, mapRepo, crsManager, l7LayerUtil }) {
return class WebMapV3 extends SuperClass {
constructor(mapId, options, mapOptions = {}) {
super();
this.mapId = mapId;
this.options = options;
this.mapOptions = mapOptions;
this._mapResourceInfo = {};
this._relatedInfo = options.relatedInfo || {};
this._sprite = '';
this._spriteDatas = {};
this._appendLayers = false;
this._baseProjection = '';
}
initializeMap(mapInfo, map) {
this._mapInfo = mapInfo;
this._baseProjection = this._registerMapCRS(mapInfo);
if (map) {
this.map = map;
if (!crsManager.isSameProjection(this.map, this._baseProjection)) {
this.fire('projectionnotmatch');
return;
}
this._appendLayers = true;
// 处理图层管理添加 sprite
const sprite = this._mapInfo.sprite;
if (sprite) {
this._sprite = sprite;
this.map.addStyle({
sprite
});
}
this._initLayers();
return;
}
this._createMap();
}
cleanLayers(layers) {
super.cleanLayers(layers);
const l7MarkerLayers = l7LayerUtil.getL7MarkerLayers();
for (const layerId in l7MarkerLayers) {
l7LayerUtil.removeL7MarkerLayer(layerId, this.map.$l7scene);
}
}
clean(removeMap = true) {
if (this.map) {
if (this._sourceListModel) {
this._sourceListModel.destroy();
this._sourceListModel = null;
}
if (removeMap) {
const scene = this.map.$l7scene;
scene && scene.removeAllLayer();
this.map.remove();
}
this.map = null;
this._legendList = [];
this._mapResourceInfo = {};
this._sprite = '';
this._spriteDatas = {};
this.mapOptions = {};
this.options = {};
}
}
async copyLayer(id, layerInfo = {}) {
const matchLayer = this._mapInfo.layers.find(layer => layer.id === id);
if (!matchLayer || this._getLayerOnMap(layerInfo.id)) {
return;
}
const copyLayerId = layerInfo.id || `${matchLayer.id}_copy`;
const copyLayer = { ...matchLayer, ...layerInfo, id: copyLayerId };
if (l7LayerUtil.isL7Layer(copyLayer)) {
const layers = [copyLayer];
const params = this._getAddL7LayersParams(layers, this._mapInfo.sources, layers);
await l7LayerUtil.addL7Layers(params);
} else {
if (typeof copyLayer.source === 'object') {
this.map.addSource(copyLayer.id, copyLayer.source);
copyLayer.source = copyLayer.id;
}
this.map.addLayer(copyLayer);
}
return copyLayer;
}
updateOverlayLayer(layerInfo, features, mergeByField) {
if (layerInfo.renderSource.type === 'geojson') {
const sourceId = layerInfo.renderSource.id;
features = mergeFeatures({ sourceId, features, mergeByField, map: this.map });
const featureCollection = {
type: 'FeatureCollection',
features
};
this.map.getSource(sourceId).setData(featureCollection);
}
}
/**
* @private
* @function WebMapV3.prototype._createMap
* @description 创建地图。
*/
_createMap() {
let {
name = '',
center = new mapRepo.LngLat(0, 0),
zoom = 0,
bearing = 0,
pitch = 0,
minzoom,
maxzoom,
sprite = ''
} = this._mapInfo;
center = this.mapOptions.center || center;
zoom = this.mapOptions.zoom || zoom;
bearing = this.mapOptions.bearing || bearing;
pitch = this.mapOptions.pitch || pitch;
const fontFamilys = this._getLabelFontFamily();
// 初始化 map
const mapOptions = {
...this.mapOptions,
transformRequest: this._getTransformRequest(),
container: this.options.target,
crs: this._baseProjection,
center,
zoom,
style: {
sprite,
name,
version: 8,
sources: {},
layers: []
},
minZoom: minzoom,
maxZoom: maxzoom,
bearing,
pitch,
localIdeographFontFamily: fontFamilys || ''
};
this.map = new MapManager(mapOptions);
this._sprite = sprite;
this.fire('mapinitialized', { map: this.map });
this.map.on('load', () => {
this._initLayers();
});
}
_getTransformRequest() {
if (this.mapOptions.transformRequest) {
return this.mapOptions.transformRequest;
}
return (url, resourceType) => {
if (resourceType === 'Tile') {
const withCredentials = this.options.iportalServiceProxyUrlPrefix && url.indexOf(this.options.iportalServiceProxyUrlPrefix) >= 0;
return {
url: url,
credentials: withCredentials ? 'include' : undefined,
...(this.options.tileTransformRequest && this.options.tileTransformRequest(url))
};
}
return { url };
}
}
_registerMapCRS(mapInfo) {
const { crs } = mapInfo;
let epsgCode = crs;
if (typeof crs === 'object') {
crsManager.registerCRS(crs);
epsgCode = crs.name;
}
return epsgCode;
}
/**
* @private
* @function WebMapV3.prototype._initLayers
* @description emit 图层加载成功事件。
*/
async _initLayers() {
await this._getSpriteDatas();
if (Object.prototype.toString.call(this.mapId) === '[object Object]') {
this.mapParams = {
title: this._mapInfo.name,
description: this._relatedInfo.description
};
if (this._relatedInfo.projectInfo) {
this._mapResourceInfo = JSON.parse(this._relatedInfo.projectInfo);
}
this._createMapRelatedInfo();
this._addLayersToMap();
return;
}
this._getMapRelatedInfo()
.then((relatedInfo) => {
this.mapParams = {
title: this._mapInfo.name,
description: relatedInfo.description
};
this._mapResourceInfo = JSON.parse(relatedInfo.projectInfo);
this._createMapRelatedInfo();
this._addLayersToMap();
})
.catch((error) => {
this.fire('mapcreatefailed', { error: error });
console.error(error);
});
}
/**
* @private
* @function WebMapV3.prototype._createMapRelatedInfo
* @description 创建地图相关资源。
*/
_createMapRelatedInfo() {
const { glyphs } = this._mapInfo;
for (let key in glyphs) {
this.map.style.addGlyphs(key, glyphs[key]);
}
}
/**
* @private
* @function WebMapV3.prototype._getMapRelatedInfo
* @description 获取地图关联信息的 JSON 信息。
*/
_getMapRelatedInfo() {
const mapResourceUrl = transformUrl(
Object.assign({ url: `${this.options.server}web/maps/${this.mapId}` }, this.options)
);
return FetchRequest.get(mapResourceUrl, null, { withCredentials: this.options.withCredentials }).then((response) =>
response.json()
);
}
/**
* @private
* @function WebMapV3.prototype._addLayersToMap
* @description emit 图层加载成功事件。
*/
async _addLayersToMap() {
try {
const { sources, layers, layerCatalog, catalogs } = this._setUniqueId(this._mapInfo, this._mapResourceInfo);
Object.assign(this._mapInfo, {
sources,
layers,
metadata: Object.assign(this._mapInfo.metadata, { layerCatalog })
});
Object.assign(this._mapResourceInfo, { catalogs });
const mapboxglLayers = layers.filter((layer) => !l7LayerUtil.isL7Layer(layer));
mapboxglLayers.forEach((layer) => {
if (layer.metadata && layer.metadata.reused) {
return;
}
layer.source && !this.map.getSource(layer.source) && this.map.addSource(layer.source, sources[layer.source]);
// L7才会用到此属性
if (layer.type === 'symbol' && layer.layout['text-z-offset'] === 0) {
delete layer.layout['text-z-offset'];
}
this.map.addLayer(layer);
});
const l7Layers = layers.filter((layer) => l7LayerUtil.isL7Layer(layer));
if (l7Layers.length > 0) {
const params = this._getAddL7LayersParams(layers, sources, l7Layers);
await l7LayerUtil.addL7Layers(params);
}
this._createLegendInfo();
this._sendMapToUser();
} catch (error) {
this.fire('mapcreatefailed', { error, map: this.map });
console.error(error);
}
}
_getAddL7LayersParams(layers, sources, l7Layers) {
return {
map: this.map,
webMapInfo: { ...this._mapInfo, layers, sources },
l7Layers,
spriteDatas: this._spriteDatas,
options: {
...this.options,
emitterEvent: this.fire.bind(this),
transformRequest: this._getTransformRequest()
}
}
}
/**
* @private
* @function WebMapV3.prototype._setUniqueId
* @description 返回唯一 id 的 sources 和 layers。
* @param {Object} mapInfo - map 信息。
*/
_setUniqueId(style, projectInfo) {
const unspportedLayers = this._handleUnSupportedLayers(style);
const layersToMap = JSON.parse(JSON.stringify(style.layers)).filter((layer) => {
return !unspportedLayers.includes(layer.id);
});
const nextSources = {};
const sourcesIdChangedMap = {};
const layerIdToChange = [];
const timestamp = `_${+new Date()}`;
for (const sourceId in style.sources) {
let nextSourceId = sourceId;
if (this.map.getSource(sourceId)) {
nextSourceId = sourceId + timestamp;
}
sourcesIdChangedMap[nextSourceId] = sourceId;
nextSources[nextSourceId] = style.sources[sourceId];
for (const layer of layersToMap) {
if (layer.source === sourceId) {
layer.source = nextSourceId;
}
}
}
for (const layer of layersToMap) {
const originId = layer.id;
const existLayer = this._getLayerOnMap(layer.id);
if (existLayer) {
if (
this.options.checkSameLayer &&
isSameRasterLayer(nextSources[layer.source], this.map.getSource(existLayer.source))
) {
layer.metadata = layer.metadata || {};
layer.metadata.reused = true;
layer.source = sourcesIdChangedMap[layer.source];
} else {
const layerId = layer.id + timestamp;
layer.id = layerId;
}
}
layerIdToChange.push({ originId: originId, renderId: layer.id, id: originId });
}
const layerCatalogFromMapJson = JSON.parse(JSON.stringify(style.metadata.layerCatalog), 'parts');
this._updateLayerCatalogsId({
loopData: JSON.parse(JSON.stringify(layerCatalogFromMapJson)),
catalogs: layerCatalogFromMapJson,
layerIdMapList: layerIdToChange,
unspportedLayers
});
const catalogsFromProjectInfo = JSON.parse(JSON.stringify(projectInfo.catalogs || []));
this._updateLayerCatalogsId({
loopData: JSON.parse(JSON.stringify(catalogsFromProjectInfo)),
catalogs: catalogsFromProjectInfo,
layerIdMapList: layerIdToChange,
catalogTypeField: 'catalogType',
layerIdsField: 'layersContent',
unspportedLayers
});
return {
sources: nextSources,
layers: layersToMap,
layerCatalog: layerCatalogFromMapJson,
catalogs: catalogsFromProjectInfo
};
}
_getLayerOnMap(layerId) {
const overlayLayer = this.map.overlayLayersManager[layerId];
if (overlayLayer) {
return overlayLayer;
}
const l7MarkerLayers = l7LayerUtil.getL7MarkerLayers();
const l7MarkerLayer = l7MarkerLayers[layerId];
if (l7MarkerLayer) {
return l7MarkerLayer;
}
return this.map.getLayer(layerId);
}
_findLayerCatalog(items, id) {
for (const item of items) {
if (item.id === id) {
return item;
}
if (item.children) {
const found = this._findLayerCatalog(item.children, id);
if (found) {
return found;
}
}
}
return null;
}
_deleteLayerCatalog(catalogs, id) {
for (let index = 0; index < catalogs.length; index++) {
const catalog = catalogs[index];
if (catalog.id === id) {
catalogs.splice(index, 1);
break;
}
if (catalog.children) {
this._deleteLayerCatalog(catalog.children, id);
}
}
}
_updateLayerCatalogsId({
loopData,
catalogs,
layerIdMapList,
catalogTypeField = 'type',
layerIdsField = 'parts',
unspportedLayers
}) {
loopData.forEach((loopItem) => {
const { id, children } = loopItem;
if (loopItem[catalogTypeField] === 'group') {
this._updateLayerCatalogsId({
loopData: children,
catalogs,
layerIdMapList,
catalogTypeField,
layerIdsField,
unspportedLayers
});
return;
}
const renderLayers = getLayerCatalogRenderLayers(loopItem[layerIdsField], id, layerIdMapList);
const matchLayer = layerIdMapList.find((item) => item.originId === renderLayers[0]);
if (matchLayer) {
const catalog = this._findLayerCatalog(catalogs, id);
catalog.id = matchLayer.renderId;
catalog.reused = matchLayer.reused;
if (catalog[layerIdsField]) {
catalog[layerIdsField] = this._renameLayerIdsContent(catalog[layerIdsField], layerIdMapList);
}
return;
}
if (unspportedLayers.includes(id) || renderLayers.some((layerId) => unspportedLayers.includes(layerId))) {
this._deleteLayerCatalog(catalogs, id);
}
});
}
/**
* @private
* @function WebMapV3.prototype._sendMapToUser
* @description emit 图层加载成功事件。
*/
_sendMapToUser() {
this._sourceListModel = new SourceListModelV3({
map: this.map,
appendLayers: this._appendLayers,
mapInfo: this._mapInfo,
mapResourceInfo: this._mapResourceInfo,
legendList: this._legendList,
l7LayerUtil
});
this._sourceListModel.on({
layerupdatechanged: (params) => {
this.fire('layerupdatechanged', params);
}
});
this.fire('mapcreatesucceeded', { map: this.map, mapparams: this.mapParams, layers: this.getSelfAppreciableLayers() });
}
_renameLayerIdsContent(layerIds, layerIdRenameMapList) {
if (!layerIds) {
return layerIds;
}
return layerIds.map((id) => {
const matchItem = layerIdRenameMapList.find((item) => item.originId === id);
return matchItem.renderId;
});
}
_parseRendererStyleData(renderer) {
// 根据 map 的工程信息返回结果看,聚合图层的 renderer 是对象 其他图层是数组
if (renderer instanceof Array) {
return renderer;
}
return [renderer];
}
/**
* @private
* @function WebMapV3.prototype._getLabelFontFamily
* @description 获取图层字体类型。
*/
_getLabelFontFamily() {
const fonts = ['sans-serif'];
const layers = this._mapInfo.layers;
if (layers && layers.length > 0) {
layers.forEach((layer) => {
const textFont = (layer.layout && layer.layout['text-font']) || [];
fonts.push(...textFont);
});
}
const fontFamilys = fonts.join(',');
return fontFamilys;
}
/**
* @private
* @function WebMapV3.prototype._getSpriteDatas
* @description 获取雪碧图信息。
*/
_getSpriteDatas() {
const sprite = this._sprite;
if (!sprite) {
return;
}
const spriteUrls = [];
if (typeof sprite === 'string') {
spriteUrls.push(sprite);
} else if (typeof sprite === 'object') {
Object.keys(sprite).forEach((sourceId) => {
spriteUrls.push(sprite[sourceId]);
});
}
return Promise.all(spriteUrls.map((url) => this._getSpriteData(url))).then((allResults) => {
allResults.forEach((result) => {
this._spriteDatas = {...this._spriteDatas, ...result};
});
return;
});
}
_getSpriteData(sprite) {
const url = sprite.replace(/.+(web\/maps\/.+)/, `${this.options.server}$1`);
return FetchRequest.get(url, null, { withCredentials: this.options.withCredentials })
.then((response) => {
return response.json();
});
}
_createLegendInfo() {
const { catalogs = [] } = this._mapResourceInfo;
const originLayers = getLayerInfosFromCatalogs(catalogs, 'catalogType');
for (const layer of originLayers) {
const { renderer, label } = layer.visualization || {};
if (!renderer) {
continue;
}
const layerFromMapInfo = getMainLayerFromCatalog(layer.layersContent, layer.id, this._mapInfo.layers);
let themeField;
const sourceInfo = this._mapInfo.sources[layerFromMapInfo.source];
if ('clusterField' in sourceInfo) {
themeField = sourceInfo.clusterField;
}
const nextLayer = Object.assign({}, layerFromMapInfo, { title: layer.title, themeField });
const styleSettings = this._parseRendererStyleData(renderer);
// 线面文本标签
if (label) {
styleSettings.push({...label, type: 'text'});
if (label.symbolsContent && label.symbolsContent.value.symbolId) {
styleSettings.push({...label, type: 'symbol'});
}
}
// 点文本标签
if (styleSettings[0].textField && styleSettings[0].textField.value) {
styleSettings.push({
...styleSettings[0],
type: 'text'
});
}
const layerLegends = styleSettings.reduce((legends, styleSetting) => {
const legendItems = this._createLayerLegendList(nextLayer, styleSetting);
legendItems && legends.push(...legendItems);
return legends;
}, []);
this._legendList.push(...layerLegends);
}
}
_getAliasKey(renderType, key) {
if (renderType === 'isoline3D' && key === 'dashArray') {
return 'lineDasharray';
}
return key;
}
_transStyleKeys(renderType, keys) {
return keys.map((key) => this._getAliasKey(renderType, key));
}
_transStyleSetting(renderType, styleSetting) {
for (const key in styleSetting) {
const aliasKey = this._getAliasKey(renderType, key);
if (aliasKey !== key) {
styleSetting[aliasKey] = styleSetting[key];
}
}
}
_getLegendSimpleStyle(styleSetting, keys) {
const simpleStyle = {};
if (keys) {
const simpleKeys = keys.filter((k) => styleSetting[k] && styleSetting[k].type === 'simple');
simpleKeys.forEach((k) => {
if (k === 'outlineColor' && !(styleSetting['antialias'] || {}).value) {
return;
}
simpleStyle[k] = (styleSetting[k] || {}).value;
});
}
return simpleStyle;
}
_getLegendRenderType(renderType) {
switch (renderType) {
case 'text':
return LEGEND_RENDER_TYPE.TEXT;
case 'circle':
case 'symbol':
case 'column':
return LEGEND_RENDER_TYPE.POINT;
case 'heatGrid':
case 'heatHexagon':
case 'heat3DGrid':
case 'heat3DHexagon':
return LEGEND_RENDER_TYPE.BUILTINSYMBOL;
case 'line':
case 'isoline3D':
return LEGEND_RENDER_TYPE.LINE;
case 'fill':
return LEGEND_RENDER_TYPE.FILL;
case 'fillExtrusion':
return LEGEND_RENDER_TYPE.FILLEXTRUSION;
case 'animatePoint':
return LEGEND_RENDER_TYPE.ANIMATEPOINT;
case 'line3D':
case 'animateLine':
return LEGEND_RENDER_TYPE.ANIMATELINE;
case 'radarPoint':
return LEGEND_RENDER_TYPE.RADARPOINT;
}
}
_getLegendShape(renderType, styleSetting) {
switch (renderType) {
case 'text':
return LEGEND_SHAPE_TYPE.TEXT;
case 'circle':
case 'symbol':
return LEGEND_SHAPE_TYPE.POINT;
case 'column': {
const symbolIds = {
cylinder: LEGEND_SHAPE_TYPE.POINT,
triangleColumn: LEGEND_SHAPE_TYPE.TRIANGLE,
squareColumn: LEGEND_SHAPE_TYPE.RECTANGLE,
hexagonColumn: LEGEND_SHAPE_TYPE.HEXAGON
};
return symbolIds[styleSetting.shape.value] || LEGEND_SHAPE_TYPE.POINT;
}
case 'heatHexagon':
case 'heat3DHexagon':
return LEGEND_SHAPE_TYPE.HEXAGON;
case 'line':
case 'isoline3D':
return LEGEND_SHAPE_TYPE.LINE;
case 'fill':
case 'heatGrid':
case 'heat3DGrid':
case 'fillExtrusion':
return LEGEND_SHAPE_TYPE.RECTANGLE;
case 'animatePoint':
return LEGEND_SHAPE_TYPE.ANIMATEPOINT;
case 'animateLine':
case 'line3D':
return LEGEND_SHAPE_TYPE.ANIMATELINE;
case 'radarPoint':
return LEGEND_SHAPE_TYPE.RADARPOINT;
case 'heat':
case 'heat3D':
return LEGEND_SHAPE_TYPE.LINEGRADIENT;
}
}
/**
* 1) 无数据驱动时;
* 2) 只有一个颜色数据驱动,且性线数据驱动时
* 以上两种情况图例中需要单独的显示符号项
* 是否显示图例单项
*/
_isShowLegendSingleItem(dataKeys, isLinearColor) {
return dataKeys.length === 0 || (dataKeys.length === 1 && dataKeys[0] === 'color' && isLinearColor);
}
_isWebsymbolById(id){
const a = ['line-', 'polygon-', 'point-'];
return a.some((el) => id && id.startsWith(el));
}
/**
* 获取icon-image 的sdf状态
* 目前webSymbol为false, 基本符号为true, 雪碧图从json中获取sdf的状态
*/
_getSymbolSDFStatus(id, spriteJson) {
if (this._isWebsymbolById(id)) {
return false;
}
if (this._getIconById(id)) {
return true;
}
return spriteJson[id] && spriteJson[id].sdf || false;
}
_isAllPicturePoint(symbolsContent, spriteJson) {
if (symbolsContent.type === 'simple') {
return !this._getSymbolSDFStatus(symbolsContent.value.symbolId, spriteJson);
} else {
return [...symbolsContent.values, { value: symbolsContent.defaultValue }]
.filter((v) => v.value.symbolId)
.every((v) => {
return !this._getSymbolSDFStatus(v.value.symbolId, spriteJson);
});
}
}
_isAllPictureSymbolSaved(symbolType, symbolsContent, spriteJson) {
if (!symbolsContent) {
return false;
}
if (symbolType === 'point') {
return this._isAllPicturePoint(symbolsContent, spriteJson);
}
const currentType = symbolsContent.type;
if (currentType === 'simple') {
return !!this._getImageIdFromValue(symbolsContent.value.style, SymbolType[symbolType]).length;
}
const styles = symbolsContent.values.map((v) => v.value).concat(symbolsContent.defaultValue);
return styles.every((v) => {
return !!this._getImageIdFromValue(v.style, SymbolType[symbolType]).length;
});
}
_getDataDrivenStyleKeys(legendType, keys, styleSetting) {
const DataDrivenStyleKeyObj = {
[LEGEND_RENDER_TYPE.TEXT]: LegendTextDataDrivenStyleKey
};
const porpertyKeys = DataDrivenStyleKeyObj[legendType] || keys;
const dataKeys = porpertyKeys.filter(
(k) => styleSetting[k] && styleSetting[k].type !== 'simple'
);
return dataKeys;
}
_createLayerLegendList(layer, styleSetting) {
const layerId = layer.id;
const layerTitle = layer.title;
const textFieldName = styleSetting.type === 'text' && styleSetting.textField && styleSetting.textField.value.replace(/^\{|\}$/g, '');
const commonStyleOptions = {
themeField: layer.themeField || styleSetting.field,
layerId,
layerTitle
};
const renderType = styleSetting.type || layer.type;
const legendRenderType = this._getLegendRenderType(renderType);
const shape = this._getLegendShape(renderType, styleSetting);
if (['heat', 'heat3D'].includes(renderType)) {
const colorKeyMap = {
heat: 'heatmap-color',
heat3D: 'heatmap-extrusion-color'
};
const colors = this._heatColorToGradient((layer.paint || {})[colorKeyMap[renderType]]);
return [
{
...commonStyleOptions,
styleGroup: [
{
style: {
type: LEGEND_STYLE_TYPES.STYLE,
shape,
colors
}
}
]
}
];
}
const styleKeys = LEGEND_STYLE_KEYS[legendRenderType];
if (!styleKeys) {
return;
}
const keys = this._transStyleKeys(renderType, styleKeys);
this._transStyleSetting(renderType, styleSetting);
const simpleStyle = this._getLegendSimpleStyle(styleSetting, keys);
const simpleResData = this._parseLegendtyle({ legendRenderType, customValue: simpleStyle });
let dataKeys = this._getDataDrivenStyleKeys(legendRenderType, keys, styleSetting);
// 3D线,动画线
if (legendRenderType === LEGEND_RENDER_TYPE.ANIMATELINE) {
// isReplaceLineColor: 3D线,动画线:使用符号替换线颜色,图例中将不再显示线颜色
const isReplaceLineColor = styleSetting.textureBlend.value === 'replace';
const hasTexture = !!(styleSetting.symbolsContent.value && styleSetting.symbolsContent.value.symbolId);
if (isReplaceLineColor && hasTexture) {
dataKeys = dataKeys.filter((key) => key !== 'color')
}
} else {
// 其他
// isAllPic: 如果符号为图片,图例中将不再显示颜色
const symbolTypes = MAP_LAYER_TYPE_2_SYMBOL_TYPE[layer.type];
const isAllPic = this._isAllPictureSymbolSaved(symbolTypes, styleSetting.symbolsContent, this._spriteDatas);
if(isAllPic) {
dataKeys = dataKeys.filter((key) => key !== 'color')
}
}
const isLinearColor = styleSetting.color && styleSetting.color.interpolateInfo && styleSetting.color.interpolateInfo.type === 'linear';
const isShowSingleItem = this._isShowLegendSingleItem(dataKeys, isLinearColor);
const resultList = [];
if (isShowSingleItem) {
resultList.push({
...commonStyleOptions,
styleGroup: [
{
fieldValue: textFieldName || layerTitle || layerId,
style: {
...simpleResData,
shape
}
}
]
});
}
return resultList.concat(
dataKeys.map((styleField) => {
const subStyleSetting = styleSetting[styleField];
const defaultSetting = this._getSettingStyle(styleField, subStyleSetting.defaultValue, simpleStyle);
let styleGroup = [];
const custom = this._getSettingCustom(subStyleSetting);
const interpolateInfo = this._getSettingInterpolateInfo(subStyleSetting);
const params = {
legendRenderType,
styleField,
subStyleSetting,
simpleStyle,
defaultSetting,
custom,
interpolateInfo,
shape
};