/
mapbox-gl.adapter.ts
416 lines (372 loc) · 10.9 KB
/
mapbox-gl.adapter.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
import {
TerraDrawChanges,
SetCursor,
TerraDrawStylingFunction,
} from "../common";
import { Feature, LineString, Point, Polygon } from "geojson";
import mapboxgl, {
CircleLayer,
FillLayer,
LineLayer,
PointLike,
} from "mapbox-gl";
import { GeoJSONStoreFeatures, GeoJSONStoreGeometries } from "../store/store";
import { TerraDrawBaseAdapter } from "./common/base.adapter";
export class TerraDrawMapboxGLAdapter extends TerraDrawBaseAdapter {
constructor(config: { map: mapboxgl.Map; coordinatePrecision?: number }) {
super(config);
this._map = config.map;
this._container = this._map.getContainer();
}
private _map: mapboxgl.Map;
private _container: HTMLElement;
private _rendered: Record<
string,
{
pointId: string;
lineStringId: string;
polygonId: string;
}
> = {};
/**
* Clears the map of rendered layers and sources
* @returns void
* */
private clearLayers() {
Object.keys(this._rendered).forEach((key) => {
Object.keys(this._rendered[key]).forEach((geometryKey) => {
const id =
this._rendered[key][
geometryKey as "pointId" | "lineStringId" | "polygonId"
];
this._map.removeLayer(id);
// Special case for polygons as it has another id for the outline
// that we need to make sure we remove
if (geometryKey === "polygonId") {
this._map.removeLayer(id + "-outline");
}
this._map.removeSource(id);
});
});
this._rendered = {};
}
private _addGeoJSONSource(id: string, features: Feature[]) {
this._map.addSource(id, {
type: "geojson",
data: {
type: "FeatureCollection",
features: features,
},
tolerance: 0,
});
}
private _addFillLayer(id: string, mode: string) {
return this._map.addLayer({
id,
source: id,
type: "fill",
filter: [
"all",
["match", ["geometry-type"], "Polygon", true, false],
["match", ["get", "mode"], mode, true, false],
],
paint: {
"fill-color": ["get", "polygonFillColor"],
"fill-opacity": ["get", "polygonFillOpacity"],
},
} as FillLayer);
}
private _addFillOutlineLayer(id: string, mode: string, beneath?: string) {
const layer = this._map.addLayer({
id: id + "-outline",
source: id,
type: "line",
filter: [
"all",
["match", ["geometry-type"], "Polygon", true, false],
["match", ["get", "mode"], mode, true, false],
],
paint: {
"line-width": ["get", "polygonOutlineWidth"],
"line-color": ["get", "polygonOutlineColor"],
},
} as LineLayer);
if (beneath) {
this._map.moveLayer(id, beneath);
}
return layer;
}
private _addLineLayer(id: string, mode: string, beneath?: string) {
const layer = this._map.addLayer({
id,
source: id,
type: "line",
filter: [
"all",
["match", ["geometry-type"], "LineString", true, false],
["match", ["get", "mode"], mode, true, false],
],
paint: {
"line-width": ["get", "lineStringWidth"],
"line-color": ["get", "lineStringColor"],
},
} as LineLayer);
if (beneath) {
this._map.moveLayer(id, beneath);
}
return layer;
}
private _addPointLayer(id: string, mode: string, beneath?: string) {
const layer = this._map.addLayer({
id,
source: id,
type: "circle",
filter: [
"all",
["match", ["geometry-type"], "Point", true, false],
["match", ["get", "mode"], mode, true, false],
],
paint: {
"circle-stroke-color": ["get", "pointOutlineColor"],
"circle-stroke-width": ["get", "pointOutlineWidth"],
"circle-radius": ["get", "pointWidth"],
"circle-color": ["get", "pointColor"],
},
} as CircleLayer);
if (beneath) {
this._map.moveLayer(id, beneath);
}
return layer;
}
private _addLayer(
id: string,
mode: string,
featureType: "Point" | "LineString" | "Polygon",
beneath?: string
) {
if (featureType === "Point") {
this._addPointLayer(id, mode, beneath);
}
if (featureType === "LineString") {
this._addLineLayer(id, mode, beneath);
}
if (featureType === "Polygon") {
this._addFillLayer(id, mode);
this._addFillOutlineLayer(id, mode, beneath);
}
}
private _addGeoJSONLayer<T extends GeoJSONStoreGeometries>(
mode: string,
featureType: Feature<T>["geometry"]["type"],
features: Feature<T>[]
) {
const id = `td-${mode}-${featureType.toLowerCase()}`;
this._addGeoJSONSource(id, features);
this._addLayer(id, mode, featureType);
return id;
}
private _setGeoJSONLayerData<T extends GeoJSONStoreGeometries>(
mode: string,
featureType: Feature<T>["geometry"]["type"],
features: Feature<T>[]
) {
const id = `td-${mode}-${featureType.toLowerCase()}`;
(this._map.getSource(id) as any).setData({
type: "FeatureCollection",
features: features,
});
return id;
}
/**
* Returns the longitude and latitude coordinates from a given PointerEvent on the map.
* @param event The PointerEvent or MouseEvent containing the screen coordinates of the pointer.
* @returns An object with 'lng' and 'lat' properties representing the longitude and latitude, or null if the conversion is not possible.
*/
public getLngLatFromEvent(event: PointerEvent | MouseEvent) {
const { left, top } = this.getMapContainer().getBoundingClientRect();
const x = event.clientX - left;
const y = event.clientY - top;
return this.unproject(x, y);
}
/**
* Retrieves the HTML container element of the Leaflet map.
* @returns The HTMLElement representing the map container.
*/
public getMapContainer() {
return this._container;
}
/**
* Enables or disables the draggable functionality of the map.
* @param enabled Set to true to enable map dragging, or false to disable it.
*/
public setDraggability(enabled: boolean) {
if (enabled) {
this._map.dragPan.enable();
} else {
this._map.dragPan.disable();
}
}
/**
* Converts longitude and latitude coordinates to pixel coordinates in the map container.
* @param lng The longitude coordinate to project.
* @param lat The latitude coordinate to project.
* @returns An object with 'x' and 'y' properties representing the pixel coordinates within the map container.
*/
public project(lng: number, lat: number) {
const { x, y } = this._map.project({ lng, lat });
return { x, y };
}
/**
* Converts pixel coordinates in the map container to longitude and latitude coordinates.
* @param x The x-coordinate in the map container to unproject.
* @param y The y-coordinate in the map container to unproject.
* @returns An object with 'lng' and 'lat' properties representing the longitude and latitude coordinates.
*/
public unproject(x: number, y: number) {
const { lng, lat } = this._map.unproject({ x, y } as PointLike);
return { lng, lat };
}
/**
* Sets the cursor style for the map container.
* @param cursor The CSS cursor style to apply, or 'unset' to remove any previously applied cursor style.
*/
public setCursor(style: Parameters<SetCursor>[0]) {
this._map.getCanvas().style.cursor = style;
}
/**
* Enables or disables the double-click to zoom functionality on the map.
* @param enabled Set to true to enable double-click to zoom, or false to disable it.
*/
public setDoubleClickToZoom(enabled: boolean) {
if (enabled) {
this._map.doubleClickZoom.enable();
} else {
this._map.doubleClickZoom.disable();
}
}
/**
* Renders GeoJSON features on the map using the provided styling configuration.
* @param changes An object containing arrays of created, updated, and unchanged features to render.
* @param styling An object mapping draw modes to feature styling functions
*/
public render(changes: TerraDrawChanges, styling: TerraDrawStylingFunction) {
const features = [
...changes.created,
...changes.updated,
...changes.unchanged,
];
const modeFeatures: {
[key: string]: {
points: GeoJSONStoreFeatures[];
linestrings: GeoJSONStoreFeatures[];
polygons: GeoJSONStoreFeatures[];
};
} = {};
Object.keys(styling).forEach((mode) => {
if (!modeFeatures[mode]) {
modeFeatures[mode] = {
points: [],
linestrings: [],
polygons: [],
};
}
});
for (let i = 0; i < features.length; i++) {
const feature = features[i];
Object.keys(styling).forEach((mode) => {
const { properties } = feature;
if (properties.mode !== mode) {
return;
}
const styles = styling[mode](feature);
if (feature.geometry.type === "Point") {
properties.pointColor = styles.pointColor;
properties.pointOutlineColor = styles.pointOutlineColor;
properties.pointOutlineWidth = styles.pointOutlineWidth;
properties.pointWidth = styles.pointWidth;
modeFeatures[mode].points.push(feature);
} else if (feature.geometry.type === "LineString") {
properties.lineStringColor = styles.lineStringColor;
properties.lineStringWidth = styles.lineStringWidth;
modeFeatures[mode].linestrings.push(feature);
} else if (feature.geometry.type === "Polygon") {
properties.polygonFillColor = styles.polygonFillColor;
properties.polygonFillOpacity = styles.polygonFillOpacity;
properties.polygonOutlineColor = styles.polygonOutlineColor;
properties.polygonOutlineWidth = styles.polygonOutlineWidth;
modeFeatures[mode].polygons.push(feature);
}
});
}
Object.keys(styling).forEach((mode) => {
if (!modeFeatures[mode]) {
return;
}
const { points, linestrings, polygons } = modeFeatures[mode];
if (!this._rendered[mode]) {
const pointId = this._addGeoJSONLayer<Point>(
mode,
"Point",
points as Feature<Point>[]
);
const lineStringId = this._addGeoJSONLayer<LineString>(
mode,
"LineString",
linestrings as Feature<LineString>[]
);
const polygonId = this._addGeoJSONLayer<Polygon>(
mode,
"Polygon",
polygons as Feature<Polygon>[]
);
this._rendered[mode] = {
pointId,
lineStringId,
polygonId,
};
} else {
const pointId = this._setGeoJSONLayerData<Point>(
mode,
"Point",
points as Feature<Point>[]
);
this._setGeoJSONLayerData<LineString>(
mode,
"LineString",
linestrings as Feature<LineString>[]
);
this._setGeoJSONLayerData<Polygon>(
mode,
"Polygon",
polygons as Feature<Polygon>[]
);
// TODO: This logic could be better - I think this will render the selection points above user
// defined layers outside of TerraDraw which is perhaps unideal
// Ensure selection/mid points are rendered on top
this._map.moveLayer(pointId);
}
});
// TODO: Figure out why this was added?
// Probably to do with forcing style changes?
// if ((this._map as any).style) {
// // cancel the scheduled update
// if ((this._map as any)._frame) {
// (this._map as any)._frame.cancel();
// (this._map as any)._frame = null;
// }
// (this._map as any)._render();
// }
}
/**
* Clears the map and store of all rendered data layers
* @returns void
* */
public clear() {
if (this._currentModeCallbacks) {
// Clear up state first
this._currentModeCallbacks.onClear();
// Then clean up rendering
this.clearLayers();
}
}
}