wujingjing
2025-02-07 4c20089472b20319746649decbce3a11f16cb6a0
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
import { defaultsDeep } from 'lodash-es';
import type { Overlay } from 'ol';
import { Map as OpenLayerMap, View } from 'ol';
import type { Extent } from 'ol/extent';
import { getTopLeft, getWidth } from 'ol/extent';
import Tile from 'ol/layer/Tile';
import { fromLonLat, get as getProjection } from 'ol/proj';
import { XYZ } from 'ol/source';
import WMTS from 'ol/source/WMTS';
import WMTSTileGrid from 'ol/tilegrid/WMTS';
import type { ViewOptions } from 'ol/View';
import MVT from 'ol/format/MVT.js';
import VectorTileLayer from 'ol/layer/VectorTile';
import VectorTileSource from 'ol/source/VectorTile';
import { defaults as olDefaults } from 'ol/interaction';
import type { Ref } from 'vue';
import { ref } from 'vue';
import { MarkerOverlay } from './overlay/marker';
import { TileGrid } from 'ol/tilegrid';
import Style from 'ol/style/Style';
import Fill from 'ol/style/Fill';
import Stroke from 'ol/style/Stroke';
import Circle from 'ol/style/Circle';
 
export type LangType = 'zh_cn' | 'en';
export const enum GaoDeSourceType {
    /** @description 默认地图 */
    Default = 0,
    /** @description 影像地图 */
    Satellite = 1,
    /** @description 矢量地图 */
    Vector = 2,
    /** @description 影像路网 */
    SatelliteRoad = 3,
}
export const enum OverlayType {
    Marker = 'marker',
}
export const MARKER_OVERLAY_CLASS_NAME = 'marker-overlay';
 
export const gaoDeSourceTypeMap = {
    // [GaoDeSourceType.Default]: '默认地图',
    [GaoDeSourceType.Vector]: '标准地图',
 
    [GaoDeSourceType.Satellite]: '卫星地图',
    [GaoDeSourceType.SatelliteRoad]: '路网地图',
};
 
export const getGaoDeSourceUrl = (type: GaoDeSourceType, lang: LangType = 'zh_cn') => {
    const urlMap = {
        [GaoDeSourceType.Satellite]: `http://wprd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=${lang}&size=1&scl=1&style=6`,
        [GaoDeSourceType.Vector]: `http://wprd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=${lang}&size=1&scl=1&style=7`,
        [GaoDeSourceType.SatelliteRoad]: `http://wprd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=${lang}&size=1&scl=1&style=8`,
        [GaoDeSourceType.Default]: `http://wprd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=${lang}&size=1&scl=2&style=7`,
    };
    return urlMap[type];
};
type MapConfig = {
    sourceType: GaoDeSourceType;
    markerIsVisible: boolean;
};
 
type OLEventType = 'blackClick';
type OLMapOptions = {
    container: HTMLDivElement;
 
    view?: ViewOptions;
} & MapConfig;
 
const resolutions = [];
for (let i = 0; i <= 8; ++i) {
    resolutions.push(156543.03392804097 / Math.pow(2, i * 2));
}
export class OLMap {
    map: OpenLayerMap;
    source: XYZ;
    private eventMap: Map<OLEventType, Function[]>;
 
    activeSourceType: Ref<GaoDeSourceType> = ref(GaoDeSourceType.Vector);
    markerIsVisible: Ref<boolean> = ref(true);
    private emit(eventName: OLEventType, ...args: any[]) {
        const handlers = this.eventMap?.get(eventName);
        if (handlers) {
            handlers.forEach((handler) => handler(...args));
        }
    }
 
    on(eventName: OLEventType, handler: Function) {
        if (!this.eventMap) {
            this.eventMap = new Map();
        }
 
        if (!this.eventMap.has(eventName)) {
            this.eventMap.set(eventName, []);
        }
 
        this.eventMap.get(eventName).push(handler);
    }
 
    off(eventName: OLEventType, handler: Function) {
        const handlers = this.eventMap.get(eventName);
        if (handlers) {
            const index = handlers.indexOf(handler);
            if (index > -1) {
                handlers.splice(index, 1);
            }
        }
    }
 
    constructor(options: OLMapOptions) {
        const { container, view, sourceType, markerIsVisible } = defaultsDeep(options, {
            view: {
                center: [13247019.404399557, 4721671.572580107],
                zoom: 8,
            },
            sourceType: GaoDeSourceType.Vector,
            markerIsVisible: true,
        } as OLMapOptions) as OLMapOptions;
        this.source = new XYZ({
            crossOrigin: 'anonymous',
            /** @description 高德地图最大支持18级, 超过会显示空白 */
            maxZoom: 18,
            /** @description 高德地图最小支持3级, 小于3级会显示空白 */
            minZoom: 3,
        });
 
        // this.source = this.getWMTS();
        const layer = new Tile({
            source: this.source,
        });
        this.map = new OpenLayerMap({
            target: container, // 绑定 DOM 容器
            layers: [layer], // 添加图层
            view: new View(view),
            interactions: olDefaults({ doubleClickZoom: false }),
        });
        this.activeSourceType.value = sourceType;
        this.markerIsVisible.value = markerIsVisible;
        this.applySourceType(this.activeSourceType.value);
        this.listenMapClick();
        this.addBasicControl();
    }
 
    applySourceType(type: GaoDeSourceType = GaoDeSourceType.Vector) {
        const url = getGaoDeSourceUrl(type);
        this.source.setUrl(url);
    }
 
    setSourceType(type: GaoDeSourceType = GaoDeSourceType.Vector) {
        this.activeSourceType.value = type;
        this.applySourceType(type);
    }
    addMarkerLayer(dataList: any[], options: any) {
        const { markerOpt } = options;
        const markers: Overlay[] = [];
 
        // 创建标记点
        dataList.forEach((item, index) => {
            const marker = this.createMarker(`marker-${index}`, item, markerOpt);
            markers.push(marker);
            this.map.addOverlay(marker);
        });
 
        // 计算并调整视图范围
        this.adjustViewToOverlays(markers);
    }
 
    createEleOverlay(dom: string | HTMLElement, position = [0, 0]) {
        const ele = typeof dom === 'string' ? (document.querySelector(dom) as HTMLElement) : dom;
        if (!ele) return;
        const eleOverlay = new MarkerOverlay({
            element: ele,
            position: position,
            positioning: 'top-left',
            stopEvent: false,
            className: 'z-[999]',
        });
        eleOverlay.setVisible(this.markerIsVisible.value);
 
        return eleOverlay;
    }
 
    private createMarker(id: string, item: any, markerOpt: any): Overlay {
        // 创建图片元素
        const markerImg = document.createElement('img');
        markerImg.src = markerOpt.icon.url;
        markerImg.style.width = `${markerOpt.icon.size}px`;
        markerImg.style.height = `${markerOpt.icon.size}px`;
        markerImg.style.cursor = 'pointer';
        markerImg.style.userSelect = 'none';
 
        const position = fromLonLat(item.position);
 
        // 创建 Overlay
        const overlay = new MarkerOverlay({
            id,
            className: MARKER_OVERLAY_CLASS_NAME,
            element: markerImg,
            position: position,
            positioning: 'center-center',
            stopEvent: false,
        });
 
        overlay.set('extData', item.extData);
        overlay.set('type', OverlayType.Marker);
        // 添加点击事件
        markerImg.addEventListener('click', (event) => {
            if (markerOpt.icon.selectUrl) {
                markerImg.src = markerOpt.icon.selectUrl;
            }
            markerOpt.click?.(event, overlay, item.extData, position);
        });
 
        return overlay;
    }
 
    adjustViewToMarkers() {
        const overlays = this.map.getOverlays().getArray();
 
        const filteredOverlays = overlays.filter((overlay) => {
            const type = overlay.get('type');
            return type === OverlayType.Marker;
        });
        this.adjustViewToOverlays(filteredOverlays);
    }
 
    adjustViewToOverlays(overlays: Overlay[]) {
        if (overlays.length === 0) return;
        const extent = overlays.reduce<number[] | null>((ext, item) => {
            const coord = item.getPosition();
 
            if (!ext) {
                return [coord[0], coord[1], coord[0], coord[1]];
            }
            return [Math.min(ext[0], coord[0]), Math.min(ext[1], coord[1]), Math.max(ext[2], coord[0]), Math.max(ext[3], coord[1])];
        }, null);
 
        if (extent) {
            this.fitExtend(extent);
        }
    }
 
    private fitExtend(extent: Extent) {
        this.map.getView().fit(extent, {
            padding: [50, 50, 50, 50], // 设置边距,使标记点不会太靠近地图边缘
            duration: 0, // 动画持续时间(毫秒)
            maxZoom: 15, // 限制最大缩放级别,防止单个设备时缩放过大
        });
    }
    /**
     * 监听地图空白区域点击
     */
    listenMapClick() {
        this.map.on('click', (event) => {
            const feature = this.map.forEachFeatureAtPixel(event.pixel, (feature) => feature);
 
            if (!feature) {
                // overlay 无法判断
                this.emit('blackClick', event);
            }
        });
    }
 
    toggleMarkerOverlayVisible(visible: boolean) {
        const overlays = this.map.getOverlays();
        overlays.forEach((overlay) => {
            if (overlay instanceof MarkerOverlay) {
                const overlayElement = overlay.getElement();
                if (overlayElement) {
                    overlayElement.style.visibility = visible ? 'visible' : 'hidden';
                }
            }
        });
        this.markerIsVisible.value = visible;
    }
 
    getConfig(): MapConfig {
        return {
            sourceType: this.activeSourceType.value,
            markerIsVisible: this.markerIsVisible.value,
        };
    }
 
    setConfig(config: MapConfig) {
        this.activeSourceType.value = config.sourceType;
        this.markerIsVisible.value = config.markerIsVisible;
        this.applySourceType(this.activeSourceType.value);
        this.toggleMarkerOverlayVisible(this.markerIsVisible.value);
    }
 
    private addBasicControl() {
        // this.map.addControl(new ZoomSlider());
        // this.map.addControl(new FullScreen());
        const container = this.map.getViewport();
        if (!container) return;
        const olZoom = container.querySelector('.ol-zoom') as HTMLElement;
        if (!olZoom) return;
        olZoom.style.display = 'none';
    }
 
    /**
     * 放大地图
     */
    zoomIn() {
        const view = this.map.getView();
        const zoom = view.getZoom();
        view.setZoom(zoom + 1);
    }
 
    /**
     * 缩小地图
     */
    zoomOut() {
        const view = this.map.getView();
        const zoom = view.getZoom();
        view.setZoom(zoom - 1);
    }
 
    private tileUrlFunction(url) {
        return (tileCoord) =>
            url
                .replace('{z}', String(tileCoord[0] * 2 - 1))
                .replace('{x}', String(tileCoord[1]))
                .replace('{y}', String(tileCoord[2]))
                .replace('{a-d}', 'abcd'.substr(((tileCoord[1] << tileCoord[0]) + tileCoord[2]) % 4, 1));
    }
 
    addCustomLayer(url: string, style?: any) {
        const vectorTileExtent = [13270414.528705932, 2994644.904997596, 13295641.139349712, 3018305.0256410106];
 
        const vectorTileLayer = new VectorTileLayer({
            source: new VectorTileSource({
                format: new MVT(),
                url: url,
            }),
            extent: vectorTileExtent,
            style: style
        });
        this.map.addLayer(vectorTileLayer);
        return vectorTileLayer;
    }
 
    getWMTS = () => {
        const projection = getProjection('EPSG:3857');
        const projectionExtent = projection.getExtent();
        const size = getWidth(projectionExtent) / 256;
        const resolutions = new Array(19);
        const matrixIds = new Array(19);
        for (let z = 0; z < 19; ++z) {
            const pow = Math.pow(2, z);
            resolutions[z] = size / pow;
            matrixIds[z] = z;
        }
        return new WMTS({
            url: 'https://wmts-service.pre-fc.alibaba-inc.com/amap/service/wmts', //WMTS 服务的 url 地址
            layer: 'map:shanghai',
            matrixSet: 'GoogleMapsCompatible',
            format: 'image/png',
            projection: projection,
            tileGrid: new WMTSTileGrid({
                origin: getTopLeft(projectionExtent),
                resolutions: resolutions,
                matrixIds: matrixIds,
            }),
            style: 'default',
            wrapX: true,
        });
    };
}