my-openlayer 2.0.0 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/core/Polygon.js CHANGED
@@ -1,529 +1,558 @@
1
- "use strict";
2
- import VectorLayer from "ol/layer/Vector";
3
- import VectorSource from "ol/source/Vector";
4
- import GeoJSON from "ol/format/GeoJSON";
5
- import { Fill, Stroke, Style, Text } from "ol/style";
6
- import { Image as ImageLayer, Heatmap } from "ol/layer";
7
- import { Geometry, LinearRing, Point } from "ol/geom";
8
- import { fromExtent } from "ol/geom/Polygon";
9
- import Feature from "ol/Feature";
10
- import ImageStatic from "ol/source/ImageStatic";
11
- import MapTools from "./MapTools";
12
- import { ValidationUtils } from '../utils/ValidationUtils';
13
- /**
14
- * Polygon 类用于处理地图上的面要素操作
15
- * 包括添加多边形、边框、图片图层、热力图等功能
16
- */
17
- export default class Polygon {
18
- /**
19
- * 构造函数
20
- * @param map OpenLayers 地图实例
21
- */
22
- constructor(map) {
23
- this.colorMap = {
24
- '0': 'rgba(255, 0, 0, 0.6)',
25
- '1': 'rgba(245, 154, 35, 0.6)',
26
- '2': 'rgba(255, 238, 0, 0.6)',
27
- '3': 'rgba(1, 111, 255, 0.6)'
28
- };
29
- if (!map) {
30
- throw new Error('Map instance is required');
31
- }
32
- this.map = map;
33
- }
34
- /**
35
- * 获取等级颜色
36
- * @param lev 等级值,支持字符串或数字
37
- * @returns 对应等级的颜色值,如果等级不存在则返回默认颜色
38
- */
39
- getLevColor(lev) {
40
- const key = lev.toString();
41
- return this.colorMap[key] || 'rgba(128, 128, 128, 0.6)';
42
- }
43
- /**
44
- * 添加地图边框图层
45
- * @param data 图层数据,必须是有效的 GeoJSON 格式
46
- * @param options 图层配置选项
47
- * @returns 创建的图层实例
48
- * @throws 当数据格式无效时抛出错误
49
- */
50
- addBorderPolygon(data, options) {
51
- ValidationUtils.validateGeoJSONData(data);
52
- const mergedOptions = {
53
- layerName: 'border',
54
- fillColor: 'rgba(255, 255, 255, 0)',
55
- ...options
56
- };
57
- const layer = this.addPolygon(data, mergedOptions);
58
- if (mergedOptions.mask) {
59
- this.setOutLayer(data);
60
- }
61
- return layer;
62
- }
63
- /**
64
- * 添加多边形图层
65
- * @param dataJSON GeoJSON 数据
66
- * @param options 图层配置选项
67
- * @returns 创建的矢量图层
68
- * @throws 当数据格式无效时抛出错误
69
- */
70
- addPolygon(dataJSON, options) {
71
- ValidationUtils.validateGeoJSONData(dataJSON);
72
- const mergedOptions = {
73
- zIndex: 11,
74
- visible: true,
75
- strokeColor: '#EBEEF5',
76
- strokeWidth: 2,
77
- fillColor: 'rgba(255, 255, 255, 0)',
78
- textFont: '14px Calibri,sans-serif',
79
- textFillColor: '#FFF',
80
- textStrokeColor: '#409EFF',
81
- textStrokeWidth: 2,
82
- ...options
83
- };
84
- // 如果指定了图层名称,先移除同名图层
85
- if (mergedOptions.layerName) {
86
- new MapTools(this.map).removeLayer(mergedOptions.layerName);
87
- }
88
- let features;
89
- try {
90
- features = new GeoJSON().readFeatures(dataJSON, mergedOptions.projectionOptOptions ?? {});
91
- }
92
- catch (error) {
93
- throw new Error(`Failed to parse GeoJSON data: ${error}`);
94
- }
95
- const layer = new VectorLayer({
96
- properties: {
97
- name: mergedOptions.layerName,
98
- layerName: mergedOptions.layerName
99
- },
100
- source: new VectorSource({ features }),
101
- zIndex: mergedOptions.zIndex
102
- });
103
- // 设置要素样式
104
- this.setFeatureStyles(features, mergedOptions);
105
- layer.setVisible(mergedOptions.visible);
106
- this.map.addLayer(layer);
107
- // 如果需要适应视图
108
- if (mergedOptions.fitView) {
109
- this.fitViewToLayer(layer);
110
- }
111
- return layer;
112
- }
113
- /**
114
- * 设置要素样式
115
- * @param features 要素数组
116
- * @param options 样式配置选项
117
- */
118
- setFeatureStyles(features, options) {
119
- features.forEach(feature => {
120
- feature.set('type', options.layerName);
121
- feature.set('layerName', options.layerName);
122
- const fillColor = options.fillColorCallBack ? options.fillColorCallBack(feature) : options.fillColor;
123
- const featureStyle = new Style({
124
- stroke: new Stroke({
125
- color: options.strokeColor,
126
- width: options.strokeWidth,
127
- lineDash: options.lineDash,
128
- lineDashOffset: options.lineDashOffset
129
- }),
130
- fill: new Fill({ color: fillColor })
131
- });
132
- // 添加文本样式
133
- if (options.textVisible) {
134
- const text = this.getFeatureText(feature, options);
135
- if (text) {
136
- featureStyle.setText(new Text({
137
- text,
138
- font: options.textFont,
139
- fill: new Fill({ color: options.textFillColor }),
140
- stroke: new Stroke({
141
- color: options.textStrokeColor,
142
- width: options.textStrokeWidth
143
- })
144
- }));
145
- }
146
- }
147
- feature.setStyle(featureStyle);
148
- });
149
- }
150
- /**
151
- * 获取要素文本
152
- * @param feature 要素对象
153
- * @param options 配置选项
154
- * @returns 文本内容
155
- */
156
- getFeatureText(feature, options) {
157
- if (options.textCallBack) {
158
- return options.textCallBack(feature) || '';
159
- }
160
- if (options.textKey) {
161
- return feature.get(options.textKey) || '';
162
- }
163
- return '';
164
- }
165
- /**
166
- * 适应图层视图
167
- * @param layer 图层对象
168
- */
169
- fitViewToLayer(layer) {
170
- const extent = layer.getSource()?.getExtent();
171
- if (extent) {
172
- this.map.getView().fit(extent, { duration: 500 });
173
- }
174
- }
175
- /**
176
- * 根据数据数组更新某个面颜色
177
- * @param layerName 图层名称
178
- * @param colorObj 颜色映射对象,键为要素属性值,值为颜色字符串
179
- * @param options 配置项
180
- * @throws 当图层不存在时抛出错误
181
- */
182
- updateFeatureColor(layerName, colorObj, options) {
183
- ValidationUtils.validateLayerName(layerName);
184
- const layers = MapTools.getLayerByLayerName(this.map, layerName);
185
- if (layers.length === 0) {
186
- throw new Error(`Layer with name '${layerName}' not found`);
187
- }
188
- const layer = layers[0];
189
- if (!(layer instanceof VectorLayer)) {
190
- throw new Error(`Layer '${layerName}' is not a vector layer`);
191
- }
192
- const mergedOptions = {
193
- strokeColor: '#EBEEF5',
194
- strokeWidth: 2,
195
- fillColor: 'rgba(255, 255, 255, 0.3)',
196
- textFont: '14px Calibri,sans-serif',
197
- textFillColor: '#FFF',
198
- textStrokeWidth: 2,
199
- ...options
200
- };
201
- const features = layer.getSource()?.getFeatures();
202
- if (!features) {
203
- console.warn(`No features found in layer '${layerName}'`);
204
- return;
205
- }
206
- features.forEach((feature) => {
207
- this.updateSingleFeatureColor(feature, colorObj, mergedOptions);
208
- });
209
- }
210
- /**
211
- * 更新单个要素的颜色
212
- * @param feature 要素对象
213
- * @param colorObj 颜色映射对象
214
- * @param options 配置选项
215
- */
216
- updateSingleFeatureColor(feature, colorObj, options) {
217
- const name = options?.textKey ? feature.get(options.textKey) : '';
218
- const newColor = colorObj?.[name] || options?.fillColor;
219
- const featureStyle = new Style({
220
- stroke: new Stroke({
221
- color: options?.strokeColor,
222
- width: options?.strokeWidth
223
- }),
224
- fill: new Fill({ color: newColor })
225
- });
226
- // 添加文本样式
227
- if (options?.textVisible) {
228
- const text = this.getFeatureText(feature, options);
229
- if (text) {
230
- featureStyle.setText(new Text({
231
- text,
232
- font: options.textFont,
233
- fill: new Fill({ color: options.textFillColor }),
234
- stroke: new Stroke({
235
- color: options.textStrokeColor,
236
- width: options.textStrokeWidth
237
- })
238
- }));
239
- }
240
- }
241
- feature.setStyle(featureStyle);
242
- }
243
- /**
244
- * 设置外围蒙版图层
245
- *
246
- * 详细文档参考 https_blog.csdn.net/?url=https%3A%2F%2Fblog.csdn.net%2Fu012413551%2Farticle%2Fdetails%2F122739501
247
- *
248
- * @param data
249
- * @param options
250
- */
251
- setOutLayer(data, options) {
252
- /** geom转坐标数组 **/
253
- function getCoordsGroup(geom) {
254
- let group = []; //
255
- const geomType = geom.getType();
256
- if (geomType === 'LineString') {
257
- group.push(geom.getCoordinates());
258
- }
259
- else if (geomType === 'MultiLineString') {
260
- group = geom.getCoordinates();
261
- }
262
- else if (geomType === 'Polygon') {
263
- group = geom.getCoordinates();
264
- }
265
- else if (geomType === 'MultiPolygon') {
266
- geom.getPolygons().forEach((poly) => {
267
- const coords = poly.getCoordinates();
268
- group = group.concat(coords);
269
- });
270
- }
271
- else {
272
- console.log('暂时不支持的类型');
273
- }
274
- return group;
275
- }
276
- /** 擦除操作 **/
277
- function erase(geom, view) {
278
- const part = getCoordsGroup(geom);
279
- if (!part) {
280
- return;
281
- }
282
- const extent = view.getProjection().getExtent();
283
- const polygonRing = fromExtent(extent);
284
- part.forEach((item) => {
285
- const linearRing = new LinearRing(item);
286
- polygonRing.appendLinearRing(linearRing);
287
- });
288
- return polygonRing;
289
- }
290
- /** 添加遮罩 **/
291
- function createShade(geom, view) {
292
- if (geom instanceof Geometry) {
293
- const source = geom.clone();
294
- const polygon = erase(source, view);
295
- const feature = new Feature({
296
- geometry: polygon
297
- });
298
- return {
299
- feature,
300
- shade: source
301
- };
302
- }
303
- }
304
- // 遮罩样式
305
- const shadeStyle = new Style({
306
- fill: new Fill({
307
- color: options?.fillColor ?? 'rgba(0,27,59,0.8)'
308
- }),
309
- stroke: new Stroke({
310
- width: options?.strokeWidth ?? 1,
311
- color: options?.strokeColor ?? 'rgba(0,27,59,0.8)'
312
- })
313
- });
314
- // 遮罩数据源
315
- const vtSource = new VectorSource();
316
- // 遮罩图层
317
- const vtLayer = new VectorLayer({
318
- source: vtSource,
319
- style: shadeStyle,
320
- zIndex: options?.zIndex ?? 12
321
- });
322
- this.map.addLayer(vtLayer);
323
- const features = new GeoJSON().readFeatures(data);
324
- const ft = features[0];
325
- const bound = ft.getGeometry();
326
- const result = createShade(bound, this.map.getView());
327
- if (result) {
328
- vtSource.addFeature(result.feature);
329
- if (options?.extent)
330
- this.map.getView().fit(result.shade);
331
- }
332
- }
333
- /**
334
- * 添加图片图层
335
- * @param imageData 图片数据,包含url和extent
336
- * @param options 配置项
337
- * @returns 创建的图片图层
338
- * @throws 当数据格式无效时抛出错误
339
- */
340
- addImageLayer(imageData, options) {
341
- // 检查是否允许空img(当存在layerName且存在同名图层时)
342
- const allowEmptyImg = !imageData.img && !!options?.layerName;
343
- ValidationUtils.validateImageData(imageData, allowEmptyImg);
344
- const mergedOptions = {
345
- opacity: 1,
346
- visible: true,
347
- zIndex: 11,
348
- layerName: 'imageLayer',
349
- ...options
350
- };
351
- // 尝试更新现有图层
352
- if (mergedOptions.layerName) {
353
- const existingLayer = this.tryUpdateExistingImageLayer(imageData, mergedOptions);
354
- if (existingLayer) {
355
- return existingLayer;
356
- }
357
- }
358
- // 创建新图层
359
- return this.createNewImageLayer(imageData, mergedOptions);
360
- }
361
- /**
362
- * 尝试更新现有图层
363
- * @private
364
- */
365
- tryUpdateExistingImageLayer(imageData, options) {
366
- const existingLayers = MapTools.getLayerByLayerName(this.map, options.layerName);
367
- if (existingLayers.length === 0) {
368
- return null;
369
- }
370
- const existingLayer = existingLayers[0];
371
- // 如果没有extent,直接设置source为undefined
372
- if (!imageData.extent) {
373
- existingLayer.setSource(undefined);
374
- }
375
- else {
376
- // 创建新的source
377
- const url = imageData.img || existingLayer.getSource()?.getUrl() || '';
378
- const newSource = new ImageStatic({
379
- url,
380
- imageExtent: imageData.extent
381
- });
382
- existingLayer.setSource(newSource);
383
- }
384
- // 更新图层属性
385
- this.updateImageLayerProperties(existingLayer, options);
386
- return existingLayer;
387
- }
388
- /**
389
- * 创建新的图像图层
390
- * @private
391
- */
392
- createNewImageLayer(imageData, options) {
393
- let source = undefined;
394
- // 只有当extent存在时才创建ImageStatic source
395
- if (imageData.extent) {
396
- source = new ImageStatic({
397
- url: imageData.img || '',
398
- imageExtent: imageData.extent
399
- });
400
- }
401
- const imageLayer = new ImageLayer({
402
- source,
403
- opacity: options.opacity,
404
- visible: options.visible
405
- });
406
- this.configureImageLayer(imageLayer, options);
407
- return this.addImageLayerToMap(imageLayer, options);
408
- }
409
- /**
410
- * 更新图层属性
411
- * @private
412
- */
413
- updateImageLayerProperties(layer, options) {
414
- if (options.opacity !== undefined) {
415
- layer.setOpacity(options.opacity);
416
- }
417
- if (options.visible !== undefined) {
418
- layer.setVisible(options.visible);
419
- }
420
- if (options.zIndex !== undefined) {
421
- layer.setZIndex(options.zIndex);
422
- }
423
- }
424
- /**
425
- * 配置图层基本属性
426
- * @private
427
- */
428
- configureImageLayer(layer, options) {
429
- layer.set('name', options.layerName);
430
- layer.set('layerName', options.layerName);
431
- layer.setZIndex(options.zIndex);
432
- }
433
- /**
434
- * 添加图层到地图并应用裁剪
435
- * @private
436
- */
437
- addImageLayerToMap(layer, options) {
438
- if (options.mapClip && options.mapClipData) {
439
- const clippedLayer = MapTools.setMapClip(layer, options.mapClipData);
440
- this.map.addLayer(clippedLayer);
441
- return clippedLayer;
442
- }
443
- this.map.addLayer(layer);
444
- return layer;
445
- }
446
- /**
447
- * 添加热力图图层
448
- * @param pointData 点数据数组
449
- * @param options 热力图配置
450
- */
451
- addHeatmap(pointData, options) {
452
- // 只有在指定layerName时才移除已存在的同名图层
453
- if (options?.layerName) {
454
- new MapTools(this.map).removeLayer(options.layerName);
455
- }
456
- const heatmapLayer = new Heatmap({
457
- source: new VectorSource(),
458
- weight: function (fea) {
459
- return fea.get('weight');
460
- },
461
- blur: options?.blur ?? 15,
462
- radius: options?.radius ?? 10,
463
- zIndex: options?.zIndex ?? 11,
464
- opacity: options?.opacity ?? 1,
465
- });
466
- // 只有在指定layerName时才设置layerName
467
- if (options?.layerName) {
468
- heatmapLayer.set('layerName', options.layerName);
469
- }
470
- this.map.addLayer(heatmapLayer);
471
- const valueKey = options?.valueKey || 'value';
472
- const max = Math.max(...pointData.map(item => item[valueKey]));
473
- pointData.forEach((item) => {
474
- heatmapLayer?.getSource().addFeature(new Feature({
475
- geometry: new Point([item.lgtd, item.lttd]),
476
- weight: item[valueKey] / max //热力值范围是【0,1】;热力值计算 = 找出数据集中的最大值,然后用值除以最大值
477
- }));
478
- });
479
- return heatmapLayer;
480
- }
481
- /**
482
- * 添加遮罩图层
483
- * @param data GeoJSON格式的遮罩数据
484
- * @param options 配置项
485
- * @returns 创建的遮罩图层
486
- * @throws 当数据格式无效时抛出错误
487
- */
488
- addMaskLayer(data, options) {
489
- ValidationUtils.validateMaskData(data);
490
- const mergedOptions = {
491
- fillColor: 'rgba(0, 0, 0, 0.5)',
492
- opacity: 1,
493
- visible: true,
494
- layerName: 'maskLayer',
495
- ...options
496
- };
497
- let features;
498
- try {
499
- features = new GeoJSON().readFeatures(data);
500
- }
501
- catch (error) {
502
- throw new Error(`Invalid GeoJSON data: ${error}`);
503
- }
504
- if (!features || features.length === 0) {
505
- console.warn('No features found in mask data');
506
- }
507
- const maskLayer = new VectorLayer({
508
- source: new VectorSource({ features }),
509
- style: new Style({
510
- fill: new Fill({
511
- color: mergedOptions.fillColor
512
- }),
513
- stroke: mergedOptions.strokeColor ? new Stroke({
514
- color: mergedOptions.strokeColor,
515
- width: mergedOptions.strokeWidth || 1
516
- }) : undefined
517
- }),
518
- opacity: mergedOptions.opacity,
519
- visible: mergedOptions.visible
520
- });
521
- maskLayer.set('layerName', mergedOptions.layerName);
522
- this.map.addLayer(maskLayer);
523
- return maskLayer;
524
- }
525
- removePolygonLayer(layerName) {
526
- new MapTools(this.map).removeLayer(layerName);
527
- this[layerName] = null;
528
- }
529
- }
1
+ "use strict";
2
+ import VectorLayer from "ol/layer/Vector";
3
+ import VectorSource from "ol/source/Vector";
4
+ import GeoJSON from "ol/format/GeoJSON";
5
+ import { Fill, Stroke, Style, Text } from "ol/style";
6
+ import { Image as ImageLayer, Heatmap } from "ol/layer";
7
+ import { Geometry, LinearRing, Point } from "ol/geom";
8
+ import { fromExtent } from "ol/geom/Polygon";
9
+ import Feature from "ol/Feature";
10
+ import ImageStatic from "ol/source/ImageStatic";
11
+ import MapTools from "./MapTools";
12
+ import { ValidationUtils } from '../utils/ValidationUtils';
13
+ /**
14
+ * Polygon 类用于处理地图上的面要素操作
15
+ * 包括添加多边形、边框、图片图层、热力图等功能
16
+ */
17
+ export default class Polygon {
18
+ /**
19
+ * 构造函数
20
+ * @param map OpenLayers 地图实例
21
+ */
22
+ constructor(map) {
23
+ this.colorMap = {
24
+ '0': 'rgba(255, 0, 0, 0.6)',
25
+ '1': 'rgba(245, 154, 35, 0.6)',
26
+ '2': 'rgba(255, 238, 0, 0.6)',
27
+ '3': 'rgba(1, 111, 255, 0.6)'
28
+ };
29
+ if (!map) {
30
+ throw new Error('Map instance is required');
31
+ }
32
+ this.map = map;
33
+ }
34
+ /**
35
+ * 获取等级颜色
36
+ * @param lev 等级值,支持字符串或数字
37
+ * @returns 对应等级的颜色值,如果等级不存在则返回默认颜色
38
+ */
39
+ getLevColor(lev) {
40
+ const key = lev.toString();
41
+ return this.colorMap[key] || 'rgba(128, 128, 128, 0.6)';
42
+ }
43
+ addBorderPolygon(data, options) {
44
+ const isUrl = typeof data === 'string';
45
+ if (!isUrl) {
46
+ ValidationUtils.validateGeoJSONData(data);
47
+ }
48
+ const mergedOptions = {
49
+ layerName: 'border',
50
+ fillColor: 'rgba(255, 255, 255, 0)',
51
+ ...options
52
+ };
53
+ // 使用类型断言来调用重载方法
54
+ const layer = isUrl
55
+ ? this.addPolygon(data, mergedOptions)
56
+ : this.addPolygon(data, mergedOptions);
57
+ if (mergedOptions.mask && !isUrl) {
58
+ this.setOutLayer(data);
59
+ }
60
+ return layer;
61
+ }
62
+ addPolygon(dataJSON, options) {
63
+ const isUrl = typeof dataJSON === 'string';
64
+ if (!isUrl) {
65
+ ValidationUtils.validateGeoJSONData(dataJSON);
66
+ }
67
+ const mergedOptions = {
68
+ zIndex: 11,
69
+ visible: true,
70
+ strokeColor: '#EBEEF5',
71
+ strokeWidth: 2,
72
+ fillColor: 'rgba(255, 255, 255, 0)',
73
+ textFont: '14px Calibri,sans-serif',
74
+ textFillColor: '#FFF',
75
+ textStrokeColor: '#409EFF',
76
+ textStrokeWidth: 2,
77
+ ...options
78
+ };
79
+ // 如果指定了图层名称,先移除同名图层
80
+ if (mergedOptions.layerName) {
81
+ new MapTools(this.map).removeLayer(mergedOptions.layerName);
82
+ }
83
+ let features;
84
+ // 根据数据类型创建 VectorSource
85
+ const source = isUrl
86
+ ? new VectorSource({
87
+ url: dataJSON,
88
+ format: new GeoJSON(mergedOptions.projectionOptOptions ?? {})
89
+ })
90
+ : (() => {
91
+ try {
92
+ features = new GeoJSON().readFeatures(dataJSON, mergedOptions.projectionOptOptions ?? {});
93
+ }
94
+ catch (error) {
95
+ throw new Error(`Failed to parse GeoJSON data: ${error}`);
96
+ }
97
+ return new VectorSource({ features });
98
+ })();
99
+ const layer = new VectorLayer({
100
+ properties: {
101
+ name: mergedOptions.layerName,
102
+ layerName: mergedOptions.layerName
103
+ },
104
+ source,
105
+ zIndex: mergedOptions.zIndex
106
+ });
107
+ // 如果不是URL,设置要素样式
108
+ if (!isUrl) {
109
+ this.setFeatureStyles(features, mergedOptions);
110
+ }
111
+ else {
112
+ // 如果是URL,需要在数据加载后设置样式
113
+ source.once('featuresloadend', () => {
114
+ const loadedFeatures = source.getFeatures();
115
+ this.setFeatureStyles(loadedFeatures, mergedOptions);
116
+ });
117
+ }
118
+ layer.setVisible(mergedOptions.visible);
119
+ this.map.addLayer(layer);
120
+ // 如果需要适应视图
121
+ if (mergedOptions.fitView && !isUrl) {
122
+ this.fitViewToLayer(layer);
123
+ }
124
+ else if (mergedOptions.fitView && isUrl) {
125
+ // 如果是URL,需要在数据加载后适应视图
126
+ source.once('featuresloadend', () => {
127
+ this.fitViewToLayer(layer);
128
+ });
129
+ }
130
+ return layer;
131
+ }
132
+ /**
133
+ * 设置要素样式
134
+ * @param features 要素数组
135
+ * @param options 样式配置选项
136
+ */
137
+ setFeatureStyles(features, options) {
138
+ features.forEach(feature => {
139
+ feature.set('type', options.layerName);
140
+ feature.set('layerName', options.layerName);
141
+ // 如果传入了自定义样式,直接使用
142
+ if (options.style) {
143
+ if (typeof options.style === 'function') {
144
+ feature.setStyle(options.style(feature));
145
+ }
146
+ else {
147
+ feature.setStyle(options.style);
148
+ }
149
+ return;
150
+ }
151
+ const fillColor = options.fillColorCallBack ? options.fillColorCallBack(feature) : options.fillColor;
152
+ const featureStyle = new Style({
153
+ stroke: new Stroke({
154
+ color: options.strokeColor,
155
+ width: options.strokeWidth,
156
+ lineDash: options.lineDash,
157
+ lineDashOffset: options.lineDashOffset
158
+ }),
159
+ fill: new Fill({ color: fillColor })
160
+ });
161
+ // 添加文本样式
162
+ if (options.textVisible) {
163
+ const text = this.getFeatureText(feature, options);
164
+ if (text) {
165
+ featureStyle.setText(new Text({
166
+ text,
167
+ font: options.textFont,
168
+ fill: new Fill({ color: options.textFillColor }),
169
+ stroke: new Stroke({
170
+ color: options.textStrokeColor,
171
+ width: options.textStrokeWidth
172
+ })
173
+ }));
174
+ }
175
+ }
176
+ feature.setStyle(featureStyle);
177
+ });
178
+ }
179
+ /**
180
+ * 获取要素文本
181
+ * @param feature 要素对象
182
+ * @param options 配置选项
183
+ * @returns 文本内容
184
+ */
185
+ getFeatureText(feature, options) {
186
+ if (options.textCallBack) {
187
+ return options.textCallBack(feature) || '';
188
+ }
189
+ if (options.textKey) {
190
+ return feature.get(options.textKey) || '';
191
+ }
192
+ return '';
193
+ }
194
+ /**
195
+ * 适应图层视图
196
+ * @param layer 图层对象
197
+ */
198
+ fitViewToLayer(layer) {
199
+ const extent = layer.getSource()?.getExtent();
200
+ if (extent) {
201
+ this.map.getView().fit(extent, { duration: 500 });
202
+ }
203
+ }
204
+ /**
205
+ * 根据数据数组更新某个面颜色
206
+ * @param layerName 图层名称
207
+ * @param colorObj 颜色映射对象,键为要素属性值,值为颜色字符串
208
+ * @param options 配置项
209
+ * @throws 当图层不存在时抛出错误
210
+ */
211
+ updateFeatureColor(layerName, colorObj, options) {
212
+ ValidationUtils.validateLayerName(layerName);
213
+ const layers = MapTools.getLayerByLayerName(this.map, layerName);
214
+ if (layers.length === 0) {
215
+ throw new Error(`Layer with name '${layerName}' not found`);
216
+ }
217
+ const layer = layers[0];
218
+ if (!(layer instanceof VectorLayer)) {
219
+ throw new Error(`Layer '${layerName}' is not a vector layer`);
220
+ }
221
+ const mergedOptions = {
222
+ strokeColor: '#EBEEF5',
223
+ strokeWidth: 2,
224
+ fillColor: 'rgba(255, 255, 255, 0.3)',
225
+ textFont: '14px Calibri,sans-serif',
226
+ textFillColor: '#FFF',
227
+ textStrokeWidth: 2,
228
+ ...options
229
+ };
230
+ const features = layer.getSource()?.getFeatures();
231
+ if (!features) {
232
+ console.warn(`No features found in layer '${layerName}'`);
233
+ return;
234
+ }
235
+ features.forEach((feature) => {
236
+ this.updateSingleFeatureColor(feature, colorObj, mergedOptions);
237
+ });
238
+ }
239
+ /**
240
+ * 更新单个要素的颜色
241
+ * @param feature 要素对象
242
+ * @param colorObj 颜色映射对象
243
+ * @param options 配置选项
244
+ */
245
+ updateSingleFeatureColor(feature, colorObj, options) {
246
+ const name = options?.textKey ? feature.get(options.textKey) : '';
247
+ const newColor = colorObj?.[name] || options?.fillColor;
248
+ const featureStyle = new Style({
249
+ stroke: new Stroke({
250
+ color: options?.strokeColor,
251
+ width: options?.strokeWidth
252
+ }),
253
+ fill: new Fill({ color: newColor })
254
+ });
255
+ // 添加文本样式
256
+ if (options?.textVisible) {
257
+ const text = this.getFeatureText(feature, options);
258
+ if (text) {
259
+ featureStyle.setText(new Text({
260
+ text,
261
+ font: options.textFont,
262
+ fill: new Fill({ color: options.textFillColor }),
263
+ stroke: new Stroke({
264
+ color: options.textStrokeColor,
265
+ width: options.textStrokeWidth
266
+ })
267
+ }));
268
+ }
269
+ }
270
+ feature.setStyle(featureStyle);
271
+ }
272
+ /**
273
+ * 设置外围蒙版图层
274
+ *
275
+ * 详细文档参考 https_blog.csdn.net/?url=https%3A%2F%2Fblog.csdn.net%2Fu012413551%2Farticle%2Fdetails%2F122739501
276
+ *
277
+ * @param data
278
+ * @param options
279
+ */
280
+ setOutLayer(data, options) {
281
+ /** geom转坐标数组 **/
282
+ function getCoordsGroup(geom) {
283
+ let group = []; //
284
+ const geomType = geom.getType();
285
+ if (geomType === 'LineString') {
286
+ group.push(geom.getCoordinates());
287
+ }
288
+ else if (geomType === 'MultiLineString') {
289
+ group = geom.getCoordinates();
290
+ }
291
+ else if (geomType === 'Polygon') {
292
+ group = geom.getCoordinates();
293
+ }
294
+ else if (geomType === 'MultiPolygon') {
295
+ geom.getPolygons().forEach((poly) => {
296
+ const coords = poly.getCoordinates();
297
+ group = group.concat(coords);
298
+ });
299
+ }
300
+ else {
301
+ console.log('暂时不支持的类型');
302
+ }
303
+ return group;
304
+ }
305
+ /** 擦除操作 **/
306
+ function erase(geom, view) {
307
+ const part = getCoordsGroup(geom);
308
+ if (!part) {
309
+ return;
310
+ }
311
+ const extent = view.getProjection().getExtent();
312
+ const polygonRing = fromExtent(extent);
313
+ part.forEach((item) => {
314
+ const linearRing = new LinearRing(item);
315
+ polygonRing.appendLinearRing(linearRing);
316
+ });
317
+ return polygonRing;
318
+ }
319
+ /** 添加遮罩 **/
320
+ function createShade(geom, view) {
321
+ if (geom instanceof Geometry) {
322
+ const source = geom.clone();
323
+ const polygon = erase(source, view);
324
+ const feature = new Feature({
325
+ geometry: polygon
326
+ });
327
+ return {
328
+ feature,
329
+ shade: source
330
+ };
331
+ }
332
+ }
333
+ // 遮罩样式
334
+ const shadeStyle = new Style({
335
+ fill: new Fill({
336
+ color: options?.fillColor ?? 'rgba(0,27,59,0.8)'
337
+ }),
338
+ stroke: new Stroke({
339
+ width: options?.strokeWidth ?? 1,
340
+ color: options?.strokeColor ?? 'rgba(0,27,59,0.8)'
341
+ })
342
+ });
343
+ // 遮罩数据源
344
+ const vtSource = new VectorSource();
345
+ // 遮罩图层
346
+ const vtLayer = new VectorLayer({
347
+ source: vtSource,
348
+ style: shadeStyle,
349
+ zIndex: options?.zIndex ?? 12
350
+ });
351
+ this.map.addLayer(vtLayer);
352
+ const features = new GeoJSON().readFeatures(data);
353
+ const ft = features[0];
354
+ const bound = ft.getGeometry();
355
+ const result = createShade(bound, this.map.getView());
356
+ if (result) {
357
+ vtSource.addFeature(result.feature);
358
+ if (options?.extent)
359
+ this.map.getView().fit(result.shade);
360
+ }
361
+ }
362
+ /**
363
+ * 添加图片图层
364
+ * @param imageData 图片数据,包含url和extent
365
+ * @param options 配置项
366
+ * @returns 创建的图片图层
367
+ * @throws 当数据格式无效时抛出错误
368
+ */
369
+ addImageLayer(imageData, options) {
370
+ // 检查是否允许空img(当存在layerName且存在同名图层时)
371
+ const allowEmptyImg = !imageData.img && !!options?.layerName;
372
+ ValidationUtils.validateImageData(imageData, allowEmptyImg);
373
+ const mergedOptions = {
374
+ opacity: 1,
375
+ visible: true,
376
+ zIndex: 11,
377
+ layerName: 'imageLayer',
378
+ ...options
379
+ };
380
+ // 尝试更新现有图层
381
+ if (mergedOptions.layerName) {
382
+ const existingLayer = this.tryUpdateExistingImageLayer(imageData, mergedOptions);
383
+ if (existingLayer) {
384
+ return existingLayer;
385
+ }
386
+ }
387
+ // 创建新图层
388
+ return this.createNewImageLayer(imageData, mergedOptions);
389
+ }
390
+ /**
391
+ * 尝试更新现有图层
392
+ * @private
393
+ */
394
+ tryUpdateExistingImageLayer(imageData, options) {
395
+ const existingLayers = MapTools.getLayerByLayerName(this.map, options.layerName);
396
+ if (existingLayers.length === 0) {
397
+ return null;
398
+ }
399
+ const existingLayer = existingLayers[0];
400
+ // 如果没有extent,直接设置source为undefined
401
+ if (!imageData.extent) {
402
+ existingLayer.setSource(undefined);
403
+ }
404
+ else {
405
+ // 创建新的source
406
+ const url = imageData.img || existingLayer.getSource()?.getUrl() || '';
407
+ const newSource = new ImageStatic({
408
+ url,
409
+ imageExtent: imageData.extent
410
+ });
411
+ existingLayer.setSource(newSource);
412
+ }
413
+ // 更新图层属性
414
+ this.updateImageLayerProperties(existingLayer, options);
415
+ return existingLayer;
416
+ }
417
+ /**
418
+ * 创建新的图像图层
419
+ * @private
420
+ */
421
+ createNewImageLayer(imageData, options) {
422
+ let source = undefined;
423
+ // 只有当extent存在时才创建ImageStatic source
424
+ if (imageData.extent) {
425
+ source = new ImageStatic({
426
+ url: imageData.img || '',
427
+ imageExtent: imageData.extent
428
+ });
429
+ }
430
+ const imageLayer = new ImageLayer({
431
+ source,
432
+ opacity: options.opacity,
433
+ visible: options.visible
434
+ });
435
+ this.configureImageLayer(imageLayer, options);
436
+ return this.addImageLayerToMap(imageLayer, options);
437
+ }
438
+ /**
439
+ * 更新图层属性
440
+ * @private
441
+ */
442
+ updateImageLayerProperties(layer, options) {
443
+ if (options.opacity !== undefined) {
444
+ layer.setOpacity(options.opacity);
445
+ }
446
+ if (options.visible !== undefined) {
447
+ layer.setVisible(options.visible);
448
+ }
449
+ if (options.zIndex !== undefined) {
450
+ layer.setZIndex(options.zIndex);
451
+ }
452
+ }
453
+ /**
454
+ * 配置图层基本属性
455
+ * @private
456
+ */
457
+ configureImageLayer(layer, options) {
458
+ layer.set('name', options.layerName);
459
+ layer.set('layerName', options.layerName);
460
+ layer.setZIndex(options.zIndex);
461
+ }
462
+ /**
463
+ * 添加图层到地图并应用裁剪
464
+ * @private
465
+ */
466
+ addImageLayerToMap(layer, options) {
467
+ if (options.mapClip && options.mapClipData) {
468
+ const clippedLayer = MapTools.setMapClip(layer, options.mapClipData);
469
+ this.map.addLayer(clippedLayer);
470
+ return clippedLayer;
471
+ }
472
+ this.map.addLayer(layer);
473
+ return layer;
474
+ }
475
+ /**
476
+ * 添加热力图图层
477
+ * @param pointData 点数据数组
478
+ * @param options 热力图配置
479
+ */
480
+ addHeatmap(pointData, options) {
481
+ // 只有在指定layerName时才移除已存在的同名图层
482
+ if (options?.layerName) {
483
+ new MapTools(this.map).removeLayer(options.layerName);
484
+ }
485
+ const heatmapLayer = new Heatmap({
486
+ source: new VectorSource(),
487
+ weight: function (fea) {
488
+ return fea.get('weight');
489
+ },
490
+ blur: options?.blur ?? 15,
491
+ radius: options?.radius ?? 10,
492
+ zIndex: options?.zIndex ?? 11,
493
+ opacity: options?.opacity ?? 1,
494
+ });
495
+ // 只有在指定layerName时才设置layerName
496
+ if (options?.layerName) {
497
+ heatmapLayer.set('layerName', options.layerName);
498
+ }
499
+ this.map.addLayer(heatmapLayer);
500
+ const valueKey = options?.valueKey || 'value';
501
+ const max = Math.max(...pointData.map(item => item[valueKey]));
502
+ pointData.forEach((item) => {
503
+ heatmapLayer?.getSource().addFeature(new Feature({
504
+ geometry: new Point([item.lgtd, item.lttd]),
505
+ weight: item[valueKey] / max //热力值范围是【0,1】;热力值计算 = 找出数据集中的最大值,然后用值除以最大值
506
+ }));
507
+ });
508
+ return heatmapLayer;
509
+ }
510
+ /**
511
+ * 添加遮罩图层
512
+ * @param data GeoJSON格式的遮罩数据
513
+ * @param options 配置项
514
+ * @returns 创建的遮罩图层
515
+ * @throws 当数据格式无效时抛出错误
516
+ */
517
+ addMaskLayer(data, options) {
518
+ ValidationUtils.validateMaskData(data);
519
+ const mergedOptions = {
520
+ fillColor: 'rgba(0, 0, 0, 0.5)',
521
+ opacity: 1,
522
+ visible: true,
523
+ layerName: 'maskLayer',
524
+ ...options
525
+ };
526
+ let features;
527
+ try {
528
+ features = new GeoJSON().readFeatures(data);
529
+ }
530
+ catch (error) {
531
+ throw new Error(`Invalid GeoJSON data: ${error}`);
532
+ }
533
+ if (!features || features.length === 0) {
534
+ console.warn('No features found in mask data');
535
+ }
536
+ const maskLayer = new VectorLayer({
537
+ source: new VectorSource({ features }),
538
+ style: new Style({
539
+ fill: new Fill({
540
+ color: mergedOptions.fillColor
541
+ }),
542
+ stroke: mergedOptions.strokeColor ? new Stroke({
543
+ color: mergedOptions.strokeColor,
544
+ width: mergedOptions.strokeWidth || 1
545
+ }) : undefined
546
+ }),
547
+ opacity: mergedOptions.opacity,
548
+ visible: mergedOptions.visible
549
+ });
550
+ maskLayer.set('layerName', mergedOptions.layerName);
551
+ this.map.addLayer(maskLayer);
552
+ return maskLayer;
553
+ }
554
+ removePolygonLayer(layerName) {
555
+ new MapTools(this.map).removeLayer(layerName);
556
+ this[layerName] = null;
557
+ }
558
+ }