-
Notifications
You must be signed in to change notification settings - Fork 640
/
Copy pathmap.ts
547 lines (473 loc) · 15.1 KB
/
map.ts
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
import type {
Bounds,
ICameraOptions,
ILngLat,
IMapConfig,
IMercator,
IPoint,
IStatusOptions,
IViewport,
MapStyleConfig,
Point,
} from '@antv/l7-core';
import { MapServiceEvent } from '@antv/l7-core';
import { DOM } from '@antv/l7-utils';
import { mat4, vec3 } from 'gl-matrix';
import Viewport from '../lib/web-mercator-viewport';
import BaseMapService from '../utils/BaseMapService';
import { toPaddingOptions } from '../utils/utils';
import BMapGLLoader from './bmapglloader';
import './logo.css';
const EventMap: {
[key: string]: any;
} = {
mapmove: 'moving',
contextmenu: 'rightclick',
camerachange: 'update',
zoomchange: 'zoomend',
};
const BMAP_API_KEY: string = 'zLhopYPPERGtpGOgimcdKcCimGRyyIsh';
const BMAP_VERSION: string = '1.0';
// TODO: 基于抽象类 BaseMap 实现,补全缺失方法,解决类型问题
export default class BMapService extends BaseMapService<BMapGL.Map> {
protected viewport: IViewport;
protected styleConfig: Record<string, any> = {
normal: [],
};
protected currentStyle: any = 'normal';
// 事件回调代理
protected evtCbProxyMap: Map<string, Map<(...args: any) => any, (...args: any) => any>> =
new Map();
public getMap() {
return this.map as any as BMapGL.Map & {
destroy: () => void;
getTilt: () => number;
enableRotate: () => void;
enableRotateGestures: () => void;
disableRotate: () => void;
disableRotateGestures: () => void;
lnglatToMercator: (lng: number, lat: number) => [number, number];
_webglPainter: {
_canvas: HTMLCanvasElement;
};
getHeading: () => number;
setDisplayOptions: (options: { indoor?: boolean }) => void;
};
}
public handleCameraChanged = () => {
this.emit('mapchange');
const map = this.getMap();
const { lng, lat } = map.getCenter();
const option = {
center: [lng, lat],
viewportHeight: map.getContainer().clientHeight,
viewportWidth: map.getContainer().clientWidth,
bearing: 360 - map.getHeading(),
pitch: map.getTilt(),
zoom: map.getZoom() - 1.75,
};
this.viewport.syncWithMapCamera(option as any);
this.updateCoordinateSystemService();
this.cameraChangedCallback(this.viewport);
};
public setBgColor(color: string): void {
this.bgColor = color;
}
public async init() {
this.viewport = new Viewport();
const {
id,
center = [121.30654632240122, 31.25744185633306],
zoom = 12,
token = BMAP_API_KEY,
mapInstance,
version = BMAP_VERSION,
mapSize = 10000,
minZoom = 0,
maxZoom = 21,
...rest
} = this.config;
this.viewport = new Viewport();
this.version = version;
this.simpleMapCoord.setSize(mapSize);
if (!(window.BMapGL || mapInstance)) {
await BMapGLLoader.load({
key: token, // 申请好的Web端开发者Key,首次调用 load 时必填
version: BMAP_VERSION, // 指定要加载的 JSAPI 的gl版本,缺省时默认为 1.0
});
}
if (mapInstance) {
// @ts-ignore
this.map = mapInstance;
this.$mapContainer = this.map.getContainer();
const point = new BMapGL.Point(center[0], center[1]);
// false,表示用户未执行centerAndZoom进行地图初始渲染
// @ts-ignore
if (!this.map.isLoaded()) {
this.map.centerAndZoom(point, zoom);
}
this.initMapByConfig(this.config);
this.map.on('update', this.handleCameraChanged);
} else {
const mapConstructorOptions = {
enableWheelZoom: true,
minZoom,
maxZoom,
...rest,
};
if (token === BMAP_API_KEY) {
console.warn(
`%c${this.configService.getSceneWarninfo('MapToken')}!`,
'color: #873bf4;font-weigh:900;font-size: 16px;',
);
}
if (!id) {
throw Error('No container id specified');
}
const mapContainer = DOM.getContainer(id);
// 存储控件等容器,百度地图实例会被卸载掉,所以实例化后需要重新挂载
// @ts-ignore
let mapChildNodes = [...mapContainer.childNodes];
// @ts-ignore
const map = new BMapGL.Map(mapContainer, mapConstructorOptions);
this.$mapContainer = map.getContainer();
mapChildNodes.forEach((child) => {
this.$mapContainer!.appendChild(child);
});
// @ts-ignore
mapChildNodes = null;
// @ts-ignore
this.map = map;
const point = new BMapGL.Point(center[0], center[1]);
this.map.centerAndZoom(point, zoom);
this.initMapByConfig(this.config);
// 监听地图相机事件
// @ts-ignore
map.on('update', this.handleCameraChanged);
}
}
public destroy(): void {
this.getMap().destroy();
}
public onCameraChanged(callback: (viewport: IViewport) => void): void {
this.cameraChangedCallback = callback;
}
// tslint:disable-next-line:no-empty
public addMarkerContainer(): void {}
public getMarkerContainer(): HTMLElement {
return this.map.getPanes().markerPane!;
}
public getCanvasOverlays() {
return this.getMap().getContainer().querySelector('#platform')?.lastChild as HTMLElement;
}
// MapEvent // 定义事件类型
public on(type: string, handle: (...args: any[]) => void): void {
if (MapServiceEvent.indexOf(type) !== -1) {
this.eventEmitter.on(type, handle);
return;
}
let cbProxyMap = this.evtCbProxyMap.get(type);
if (!cbProxyMap) {
this.evtCbProxyMap.set(type, (cbProxyMap = new Map()));
}
// 忽略重复监听回调
if (cbProxyMap.get(handle)) {
return;
}
// 对事件对象的经纬度进行统一处理l7需要的
const handleProxy = (...args: any[]) => {
if (args[0] && typeof args[0] === 'object' && !args[0].lngLat && !args[0].lnglat) {
args[0].lngLat = args[0].latlng || args[0].latLng;
}
handle(...args);
};
cbProxyMap.set(handle, handleProxy);
this.map.on(EventMap[type] || type, handleProxy);
}
public off(type: string, handle: (...args: any[]) => void): void {
if (MapServiceEvent.indexOf(type) !== -1) {
this.eventEmitter.off(type, handle);
return;
}
const handleProxy = this.evtCbProxyMap.get(type)?.get(handle);
if (!handleProxy) {
return;
}
this.evtCbProxyMap.get(type)?.delete(handle);
this.map.off(EventMap[type] || type, handleProxy);
}
public once(type: string, handler: (...args: any[]) => void): void {
this.eventEmitter.once(type, handler);
}
public getContainer(): HTMLElement | null {
return this.getMap().getContainer();
}
public getSize(): [number, number] {
const size = this.getMap().getSize();
return [size.width, size.height];
}
// 百度地图缩放等级
public getMinZoom(): number {
return this.map.getMinZoom();
}
public getMaxZoom(): number {
return this.map.getMaxZoom();
}
// get map params
public getType() {
return 'bmap';
}
public getZoom(): number {
return this.getMap().getZoom();
}
public getCenter(options?: ICameraOptions): ILngLat {
if (options?.padding) {
const originCenter = this.getCenter();
const padding = toPaddingOptions(options.padding);
const px = this.lngLatToPixel([originCenter.lng, originCenter.lat]);
const offsetPx = [(padding.right - padding.left) / 2, (padding.bottom - padding.top) / 2];
const newCenter = this.pixelToLngLat([px.x - offsetPx[0], px.y - offsetPx[1]]);
return newCenter;
}
const center = this.map.getCenter();
return {
lng: center.lng,
lat: center.lat,
};
}
public getPitch(): number {
return this.getMap().getTilt();
}
public getRotation(): number {
return 360 - this.getMap().getHeading();
}
public getBounds(): Bounds {
const bounds = this.getMap().getBounds();
const ne = bounds.getNorthEast();
const sw = bounds.getSouthWest();
return [
[sw.lng, sw.lat],
[ne.lng, ne.lat],
];
}
public getMapContainer(): HTMLElement {
return this.getMap().getContainer();
}
public getMapCanvasContainer(): HTMLElement {
return this.getMap().getContainer();
}
public getMapStyleConfig(): MapStyleConfig {
return this.styleConfig;
}
public getMapStyleValue(name: string) {
return this.styleConfig[name];
}
public setMapStyle(style: any): void {
if (this.currentStyle === style) {
return;
}
const styleVal = Array.isArray(style) ? style : this.styleConfig[style] || style;
if (Array.isArray(styleVal)) {
this.map.setMapStyleV2({
styleJson: styleVal,
});
this.currentStyle = style;
return;
}
if (typeof styleVal === 'string') {
this.map.setMapStyleV2({
styleId: styleVal,
});
this.currentStyle = style;
return;
}
}
public setRotation(rotation: number): void {
this.getMap().setHeading(rotation);
}
public zoomIn(): void {
this.getMap().zoomIn();
}
public zoomOut(): void {
this.getMap().zoomOut();
}
public panTo(p: Point): void {
this.getMap().panTo(new BMapGL.Point(p[0], p[1]));
}
public panBy(x: number, y: number): void {
this.getMap().panBy(x, y);
}
public fitBounds(bound: Bounds, fitBoundsOptions?: unknown): void {
this.map.setViewport(
bound.map((item) => new BMapGL.Point(item[0], item[1])),
fitBoundsOptions as any,
);
}
public setZoomAndCenter(zoom: number, [lng, lat]: Point): void {
this.getMap().centerAndZoom(new BMapGL.Point(lng, lat), zoom + 1.75);
}
public setCenter([lng, lat]: [number, number], options?: ICameraOptions): void {
let newCenter = { lng, lat };
if (options?.padding) {
const padding = toPaddingOptions(options.padding);
const px = this.lngLatToPixel([lng, lat]);
const offsetPx = [(padding.right - padding.left) / 2, (padding.bottom - padding.top) / 2];
newCenter = this.pixelToLngLat([px.x + offsetPx[0], px.y + offsetPx[1]]);
}
this.getMap().setCenter(new BMapGL.Point(newCenter.lng, newCenter.lat));
}
public setPitch(pitch: number): any {
this.getMap().setTilt(pitch);
}
public setZoom(zoom: number): any {
this.getMap().setZoom(zoom);
}
public setMapStatus(option: Partial<IStatusOptions>): void {
const map = this.getMap();
(Object.keys(option) as Array<keyof IStatusOptions>).map((status) => {
switch (status) {
case 'doubleClickZoom':
option.doubleClickZoom ? map.enableDoubleClickZoom() : map.disableDoubleClickZoom();
break;
case 'dragEnable':
option.dragEnable ? map.enableDragging() : map.disableDragging();
break;
case 'keyboardEnable':
option.keyboardEnable ? map.enableKeyboard() : map.disableKeyboard();
break;
case 'resizeEnable':
option.resizeEnable ? map.enableAutoResize() : map.disableAutoResize();
break;
case 'rotateEnable':
if (option.rotateEnable) {
map.enableRotate();
map.enableRotateGestures();
} else {
map.disableRotate();
map.disableRotateGestures();
}
break;
case 'zoomEnable':
if (option.zoomEnable) {
this.map.enableDoubleClickZoom();
this.map.enableScrollWheelZoom();
this.map.enablePinchToZoom();
} else {
this.map.disableDoubleClickZoom();
this.map.disableScrollWheelZoom();
this.map.disablePinchToZoom();
}
break;
case 'showIndoorMap':
map.setDisplayOptions({
indoor: !!option.showIndoorMap,
});
break;
default:
}
});
}
// coordinates methods
public meterToCoord(center: [number, number], outer: [number, number]) {
const metreDistance = this.getMap().getDistance(
new BMapGL.Point(...center),
new BMapGL.Point(...outer),
);
const [x1, y1] = this.lngLatToCoord(center);
const [x2, y2] = this.lngLatToCoord(outer);
const coordDistance = Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2));
return coordDistance / metreDistance;
}
public pixelToLngLat([x, y]: Point): ILngLat {
const lngLat = this.getMap().pixelToPoint(new BMapGL.Pixel(x, y));
return { lng: lngLat.lng, lat: lngLat.lat };
}
public lngLatToPixel([lng, lat]: Point): IPoint {
const pixel = this.getMap().pointToPixel(new BMapGL.Point(lng, lat));
return {
x: pixel.x,
y: pixel.y,
};
}
public containerToLngLat([x, y]: [number, number]): ILngLat {
const point = this.getMap().overlayPixelToPoint(new BMapGL.Pixel(x, y));
return {
lng: point.lng,
lat: point.lat,
};
}
public lngLatToContainer([lng, lat]: [number, number]): IPoint {
const overlayPixel = this.getMap().pointToOverlayPixel(new BMapGL.Point(lng, lat));
return {
x: overlayPixel.x,
y: overlayPixel.y,
};
}
public lngLatToCoord([lng, lat]: [number, number]): [number, number] {
const { x, y } = this.getMap().pointToPixel(new BMapGL.Point(lng, lat));
return [x, -y];
}
public lngLatToCoords(list: number[][] | number[][][]): any {
return list.map((item) =>
Array.isArray(item[0])
? this.lngLatToCoords(item as Array<[number, number]>)
: this.lngLatToCoord(item as [number, number]),
);
}
public lngLatToMercator([lng, lat]: [number, number], altitude: number): IMercator {
const [McLng, McLat] = this.getMap().lnglatToMercator(lng, lat);
return {
x: McLng,
y: McLat,
z: altitude,
};
}
public getModelMatrix(
lnglat: [number, number],
altitude: number,
rotate: [number, number, number],
scale: [number, number, number] = [1, 1, 1],
): number[] {
const flat = this.viewport.projectFlat(lnglat);
const modelMatrix = mat4.create();
mat4.translate(modelMatrix, modelMatrix, vec3.fromValues(flat[0], flat[1], altitude));
mat4.scale(modelMatrix, modelMatrix, vec3.fromValues(scale[0], scale[1], scale[2]));
mat4.rotateX(modelMatrix, modelMatrix, rotate[0]);
mat4.rotateY(modelMatrix, modelMatrix, rotate[1]);
mat4.rotateZ(modelMatrix, modelMatrix, rotate[2]);
return modelMatrix as unknown as number[];
}
public getCustomCoordCenter?(): [number, number] {
throw new Error('Method not implemented.');
}
public exportMap(type: 'jpg' | 'png'): string {
const renderCanvas = this.getMap()._webglPainter._canvas;
const layersPng =
type === 'jpg'
? (renderCanvas?.toDataURL('image/jpeg') as string)
: (renderCanvas?.toDataURL('image/png') as string);
return layersPng;
}
private hideLogo() {
const container = this.map.getContainer();
if (!container) {
return;
}
DOM.addClass(container, 'bmap-contianer--hide-logo');
}
private initMapByConfig(config: Partial<IMapConfig<{}>>) {
const { style, pitch = 0, rotation = 0, logoVisible = true } = config;
if (style) {
this.setMapStyle(style);
}
if (pitch) {
this.setPitch(pitch);
}
if (rotation) {
this.setRotation(rotation);
}
if (logoVisible === false) {
this.hideLogo();
}
}
}