-
Notifications
You must be signed in to change notification settings - Fork 658
Expand file tree
/
Copy pathmap.ts
More file actions
554 lines (473 loc) · 15.2 KB
/
Copy pathmap.ts
File metadata and controls
554 lines (473 loc) · 15.2 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
import type {
Bounds,
ILngLat,
IMercator,
IPoint,
IStatusOptions,
IViewport,
MapStyleConfig,
Point,
} from '@antv/l7-core';
import { MapServiceEvent } from '@antv/l7-core';
import { MercatorCoordinate } from '@antv/l7-map';
import { DOM } from '@antv/l7-utils';
import { mat4, vec3 } from 'gl-matrix';
import BaseMap from '../lib/base-map';
import Viewport from '../lib/web-mercator-viewport';
import { MapTheme } from '../utils/theme';
import './logo.css';
import TMapLoader from './maploader';
const TMAP_VERSION: string = '1.exp';
const EventMap: {
[key: string]: any;
} = {
mapmove: 'center_changed',
camerachange: ['drag', 'pan', 'rotate', 'pitch', 'zoom'],
zoomchange: 'zoom',
dragging: 'drag',
};
export default class TMapService extends BaseMap<TMap.Map> {
// @ts-ignore
protected viewport: IViewport = null;
// Zoom 偏移量,用于对齐不同地图的显示层级
protected zoomOffset: number = 1;
protected evtCbProxyMap: Map<string, Map<(...args: any) => any, (...args: any) => any>> =
new Map();
public handleCameraChanged = () => {
// Trigger map change event
this.emit('mapchange');
// resync
const map = this.map;
// @ts-ignore
const { lng, lat } = map.getCenter();
const option = {
center: [lng, lat],
// @ts-ignore
viewportHeight: map.getContainer().clientHeight,
// @ts-ignore
viewportWidth: map.getContainer().clientWidth,
// @ts-ignore
bearing: map.getHeading(),
// @ts-ignore
pitch: map.getPitch(),
zoom: map.getZoom() - 1,
};
if (this.viewport) {
this.viewport.syncWithMapCamera(option as any);
this.updateCoordinateSystemService();
this.cameraChangedCallback(this.viewport);
}
};
public async init(): Promise<void> {
this.viewport = new Viewport();
// TODO: Handle initial config
const {
id,
mapInstance,
center = [121.30654632240122, 31.25744185633306],
token,
version = TMAP_VERSION,
libraries = [],
minZoom = 3,
maxZoom = 18,
rotation = 0,
pitch = 0,
mapSize = 10000,
logoVisible = true,
...rest
} = this.config;
if (!(window.TMap || mapInstance)) {
if (!token) {
console.warn(
`%c${this.configService.getSceneWarninfo('MapToken')}!`,
'color: #873bf4;font-weigh:900;font-size: 16px;',
);
}
await TMapLoader.load({
key: token || '',
version,
libraries,
});
}
if (mapInstance) {
// If there's already a map instance, maybe not setting any other configurations
this.map = mapInstance as any;
this.mapContainer = this.map.getContainer();
if (logoVisible === false) {
this.hideLogo();
}
} else {
if (!id) {
throw Error('No container id specified');
}
const mapContainer = DOM.getContainer(id)!;
const map = new TMap.Map(mapContainer, {
maxZoom,
minZoom,
rotation,
pitch,
showControl: false,
// Tencent use (Lat, Lng) while center is (Lng, Lat)
center: new TMap.LatLng(center[1], center[0]),
...rest,
});
// @ts-ignore
this.map = map;
// @ts-ignore
this.mapContainer = map.getContainer();
if (logoVisible === false) {
this.hideLogo();
}
}
// Set tencent map canvas element position as absolute
// @ts-ignore
this.map.canvasContainer.style.position = 'absolute';
// @ts-ignore
this.map.drawContainer.classList.add('tencent-map');
// Set tencent map control layer dom index
// @ts-ignore
const controlParentContainer = this.map.controlManager.controlContainer?.parentNode;
if (controlParentContainer) {
controlParentContainer.style.zIndex = 2;
}
this.simpleMapCoord.setSize(mapSize);
// May be find an integrated event replacing following events
this.map.on('drag', this.handleCameraChanged);
this.map.on('pan', this.handleCameraChanged);
this.map.on('rotate', this.handleCameraChanged);
this.map.on('pitch', this.handleCameraChanged);
this.map.on('zoom', this.handleCameraChanged);
this.map.on('resize', this.handleCameraChanged);
// Trigger camera change after init
this.handleCameraChanged();
this.bindPendingEvents();
}
public destroy(): void {
// map 实例可能尚未初始化完成(如 React StrictMode 双重渲染场景下提前 destroy)
if (this.map) {
this.map.destroy();
}
// 清理 marker container(如果存在)
if (this.markerContainer && this.markerContainer.parentNode) {
this.markerContainer.parentNode.removeChild(this.markerContainer);
}
}
public onCameraChanged(callback: (viewport: IViewport) => void): void {
this.cameraChangedCallback = callback;
}
public addMarkerContainer(): void {
const container = this.map.getContainer();
this.markerContainer = DOM.create('div', 'l7-marker-container', container);
this.markerContainer.setAttribute('tabindex', '-1');
this.markerContainer.style.zIndex = '2';
}
public getMarkerContainer(): HTMLElement {
return this.markerContainer;
}
// MapEvent
public on(type: string, handle: (...args: any[]) => void): void {
if (MapServiceEvent.indexOf(type) !== -1) {
this.eventEmitter.on(type, handle);
} else {
if (!this.map) {
// 地图尚未初始化,缓存事件,init 完成后重放
this.pendingHandlers.push({ type, handler: handle });
return;
}
const onProxy = (eventName: string) => {
let cbProxyMap = this.evtCbProxyMap.get(eventName);
if (!cbProxyMap) {
this.evtCbProxyMap.set(eventName, (cbProxyMap = new Map()));
}
if (cbProxyMap.get(handle)) {
return;
}
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);
if (eventName === 'mouseover') {
this.map.getContainer().addEventListener('mouseover', (e) => {
handleProxy({ type: e.type, originalEvent: e });
});
}
this.map.on(eventName, handleProxy);
};
if (Array.isArray(EventMap[type])) {
EventMap[type].forEach((eventName: string) => {
onProxy(eventName || type);
});
} else {
onProxy(EventMap[type] || type);
}
}
}
public off(type: string, handle: (...args: any[]) => void): void {
if (MapServiceEvent.indexOf(type) !== -1) {
this.eventEmitter.off(type, handle);
return;
}
if (!this.map) {
// 地图尚未初始化,从缓存中移除
this.pendingHandlers = this.pendingHandlers.filter(
(item) => !(item.type === type && item.handler === handle),
);
return;
}
const offProxy = (eventName: string) => {
const handleProxy = this.evtCbProxyMap.get(type)?.get(handle);
if (!handleProxy) {
return;
}
this.evtCbProxyMap.get(eventName)?.delete(handle);
this.map.off(eventName, handleProxy);
};
if (Array.isArray(EventMap[type])) {
EventMap[type].forEach((eventName: string) => {
offProxy(eventName || type);
});
} else {
offProxy(EventMap[type] || type);
}
}
public once(): void {
throw new Error('Method not implemented.');
}
// get dom
public getContainer(): HTMLElement | null {
return this.map.getContainer();
}
public getSize(): [number, number] {
// @ts-ignore
return [this.map.width, this.map.height];
}
// get map status method
public getMinZoom(): number {
// @ts-ignore
return this.map.transform._minZoom;
}
public getMaxZoom(): number {
// @ts-ignore
return this.map.transform._maxZoom;
}
public setMaxZoom(max: number): void {
(this.map as any).setMaxZoom?.(max);
}
public setMinZoom(min: number): void {
(this.map as any).setMinZoom?.(min);
}
// get map params
public getType() {
return 'tmap';
}
public getZoom(): number {
return this.map.getZoom();
}
public getCenter(): ILngLat {
const { lng, lat } = this.map.getCenter();
return {
lng,
lat,
};
}
public getPitch(): number {
return this.map.getPitch();
}
public getRotation(): number {
return this.map.getRotation();
}
public getBounds(): Bounds {
const ne = this.map.getBounds().getNorthEast();
const sw = this.map.getBounds().getSouthWest();
return [
[sw.lng, sw.lat],
[ne.lng, ne.lat],
];
}
public getMapContainer(): HTMLElement {
return this.map.getContainer();
}
public getMapCanvasContainer(): HTMLElement {
return this.map.getContainer()?.getElementsByTagName('canvas')[0];
}
public getCanvasOverlays() {
return this.getMapCanvasContainer()?.nextSibling?.firstChild as HTMLElement;
}
public setBgColor(color: string): void {
this.bgColor = color;
}
public getMapStyle(): string {
return '';
}
public getMapStyleConfig(): MapStyleConfig {
return MapTheme;
}
public setMapStyle(styleId: any): void {
this.map.setMapStyleId(styleId);
}
// control with raw map
public setRotation(rotation: number): void {
this.map.setRotation(rotation);
}
public zoomIn(): void {
this.map.setZoom(this.getZoom() + 1);
}
public zoomOut(): void {
this.map.setZoom(this.getZoom() - 1);
}
public panTo([lng, lat]: Point): void {
this.map.panTo(new TMap.LatLng(lat, lng));
}
public panBy(x: number, y: number): void {
this.map.panBy([x, y]);
}
public fitBounds(bound: Bounds, fitBoundsOptions?: unknown): void {
const [sw, ne] = bound;
const swLatLng = new TMap.LatLng(sw[1], sw[0]);
const neLatLng = new TMap.LatLng(ne[1], ne[0]);
const bounds = new TMap.LatLngBounds(swLatLng, neLatLng);
// @ts-ignore
this.map.fitBounds(bounds, fitBoundsOptions);
}
public setZoomAndCenter(zoom: number, [lng, lat]: Point): void {
this.map.setCenter(new TMap.LatLng(lat, lng));
this.map.setZoom(zoom);
}
public setCenter([lng, lat]: [number, number]): void {
this.map.setCenter(new TMap.LatLng(lat, lng));
}
public setPitch(pitch: number): any {
this.map.setPitch(pitch);
}
public setZoom(zoom: number): any {
this.map.setZoom(zoom);
}
public setMapStatus(option: Partial<IStatusOptions>): void {
(Object.keys(option) as Array<keyof IStatusOptions>).map((status) => {
switch (status) {
case 'doubleClickZoom':
this.map.setDoubleClickZoom(!!option.doubleClickZoom);
break;
case 'dragEnable':
this.map.setDraggable(!!option.dragEnable);
break;
case 'rotateEnable':
// @ts-ignore
this.map.setRotatable(!!option.rotateEnable);
break;
case 'zoomEnable':
this.map.setDoubleClickZoom(!!option.zoomEnable);
this.map.setScrollable(!!option.zoomEnable);
break;
case 'keyboardEnable':
case 'resizeEnable':
case 'showIndoorMap':
throw Error('Options may bot be supported');
default:
}
});
}
// coordinates methods
public meterToCoord(
[centerLon, centerLat]: [number, number],
[outerLon, outerLat]: [number, number],
) {
const metreDistance = TMap.geometry.computeDistance([
new TMap.LatLng(centerLat, centerLon),
new TMap.LatLng(outerLat, outerLon),
]);
const [x1, y1] = this.lngLatToCoord!([centerLon, centerLat]);
const [x2, y2] = this.lngLatToCoord!([outerLon, outerLat]);
const coordDistance = Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2));
return coordDistance / metreDistance;
}
public pixelToLngLat([x, y]: Point): ILngLat {
// Since tecent map didn't provide the reverse method for transforming from pixel to lnglat
// It had to be done by calculate the relative distance in container coordinates
const { lng: clng, lat: clat } = this.map.getCenter();
const { x: centerPixelX, y: centerPixelY } = this.lngLatToPixel([clng, clat]);
const { x: centerContainerX, y: centerContainerY } = this.lngLatToContainer([clng, clat]);
const result = this.map.unprojectFromContainer(
new TMap.Point(centerContainerX + (x - centerPixelX), centerContainerY + (y - centerPixelY)),
);
if (!result) {
return { lng: 0, lat: 0 };
}
return this.containerToLngLat([result.lng, result.lat]);
}
public lngLatToPixel([lng, lat]: Point): IPoint {
// @ts-ignore
const { x, y } = this.map.projectToWorldPlane(new TMap.LatLng(lat, lng));
return { x, y };
}
public containerToLngLat([x, y]: [number, number]): ILngLat {
const result = this.map.unprojectFromContainer(new TMap.Point(x, y));
if (!result) {
return { lng: 0, lat: 0 };
}
return { lng: result.lng, lat: result.lat };
}
public lngLatToContainer([lng, lat]: [number, number]): IPoint {
// @ts-ignore
const { x, y } = this.map.projectToContainer(new TMap.LatLng(lat, lng));
return { x, y };
}
public lngLatToCoord?([lng, lat]: [number, number]): [number, number] {
// TODO: Perhaps need to check the three.js coordinates
const { x, y } = this.lngLatToPixel([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(lnglat: [number, number], altitude: number): IMercator {
// Use built in mercator tools due to Tencent not provided related methods
const { x = 0, y = 0, z = 0 } = MercatorCoordinate.fromLngLat(lnglat, altitude);
return { x, y, z };
}
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);
// @ts-ignore
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.getMapCanvasContainer() as HTMLCanvasElement;
const layersPng =
type === 'jpg'
? (renderCanvas?.toDataURL('image/jpeg') as string)
: (renderCanvas?.toDataURL('image/png') as string);
return layersPng;
}
// Method on earth mode
public rotateY?(): void {
throw new Error('Method not implemented.');
}
private hideLogo() {
const container = this.map.getContainer();
if (!container) {
return;
}
DOM.addClass(container, 'tmap-contianer--hide-logo');
}
}