-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathmapboxHelper.ts
381 lines (349 loc) · 11.3 KB
/
mapboxHelper.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
import bboxClip from '@turf/bbox-clip';
import { chunk, head, sortBy } from 'lodash';
import booleanPointInPolygon from '@turf/boolean-point-in-polygon';
import booleanIntersects from '@turf/boolean-intersects';
import bbox from '@turf/bbox';
import lineIntersect from '@turf/line-intersect';
import lineSlice from '@turf/line-slice';
import WebMercatorViewport from 'viewport-mercator-project';
import { ViewState } from 'react-map-gl';
import { BBox, Coord, featureCollection } from '@turf/helpers';
import {
Feature,
FeatureCollection,
LineString,
MultiLineString,
Point,
MultiPoint,
Position,
Polygon,
} from 'geojson';
import nearestPointOnLine from '@turf/nearest-point-on-line';
import nearestPoint, { NearestPoint } from '@turf/nearest-point';
import fnDistance from '@turf/distance';
import fnExplode from '@turf/explode';
import { Zone, MapLayerMouseEvent, MapboxGeoJSONFeature } from '../types';
import { getAngle } from '../applications/editor/data/utils';
/**
* This helpers transforms a given Zone object to the related Feature object (mainly to use with
* Turf).
*/
export function zoneToFeature(zone: Zone, close = false): Feature {
switch (zone.type) {
case 'rectangle': {
const [[lat1, lon1], [lat2, lon2]] = zone.points;
return {
type: 'Feature',
properties: {},
geometry: {
type: 'Polygon',
coordinates: [
[
[lat1, lon1],
[lat2, lon1],
[lat2, lon2],
[lat1, lon2],
[lat1, lon1],
],
],
},
};
}
case 'polygon': {
return {
type: 'Feature',
properties: {},
geometry: close
? {
type: 'Polygon',
coordinates: [[...zone.points, zone.points[0]]],
}
: {
type: 'LineString',
coordinates: zone.points,
},
};
}
default:
throw new Error('Zone is neither a polygone, neither a rectangle');
}
}
/**
* Returns the BBox containing a given zone.
*/
export function zoneToBBox(zone: Zone): BBox {
if (zone.type === 'rectangle') {
const [[x1, y1], [x2, y2]] = zone.points;
return [Math.min(x1, x2), Math.min(y1, y2), Math.max(x1, x2), Math.max(y1, y2)];
}
return bbox(zoneToFeature(zone, true));
}
/**
* Helper to clip a line on a polygon.
*/
export function intersectPolygonLine(
poly: Feature<Polygon>,
line: Feature<LineString | MultiLineString>
): Feature<MultiLineString> | null {
const lines: Position[][] =
line.geometry.type === 'MultiLineString'
? line.geometry.coordinates
: [line.geometry.coordinates];
const res: Feature<MultiLineString> = {
type: 'Feature',
properties: line.properties,
geometry: {
type: 'MultiLineString',
coordinates: [],
},
};
lines.forEach((l) => {
if (l.length < 2) return;
const firstPoint: Point = { type: 'Point', coordinates: l[0] };
const lastPoint: Point = { type: 'Point', coordinates: l[l.length - 1] };
let intersections: Point[] = lineIntersect(
{ type: 'LineString', coordinates: l },
poly
).features.map((f) => f.geometry);
if (booleanPointInPolygon(firstPoint, poly)) intersections = [firstPoint].concat(intersections);
if (booleanPointInPolygon(lastPoint, poly)) intersections.push(lastPoint);
const splitters = chunk(intersections, 2).filter((pair) => pair.length === 2) as [
Point,
Point
][];
splitters.forEach(([start, end]) => {
res.geometry.coordinates.push(
lineSlice(start.coordinates, end.coordinates, { type: 'LineString', coordinates: l })
.geometry.coordinates
);
});
});
return res.geometry.coordinates.length ? res : null;
}
/**
* This helper takes a Feature *or* a FeatureCollection and a bounding zone, and returns the input
* Feature or FeatureCollection, but clipped inside the bounding zone. It filters out Points and
* MultiPoints, and clips LineStrings and MultiLineStrings using @turf/bboxClip (when possible).
*/
export function clip<T extends Feature | FeatureCollection>(tree: T, zone: Zone): T | null {
if (tree.type === 'FeatureCollection') {
return {
...tree,
features: (tree as FeatureCollection).features.flatMap((f) => {
const res = clip(f, zone);
if (!res) return [];
return [res];
}),
};
}
if (tree.type === 'Feature') {
const feature = tree as Feature;
if (feature.geometry.type === 'LineString' || feature.geometry.type === 'MultiLineString') {
if (zone.type === 'polygon') {
const clipped = intersectPolygonLine(
zoneToFeature(zone, true) as Feature<Polygon>,
feature as Feature<LineString | MultiLineString>
);
return clipped ? (clipped as T) : null;
}
const clipped = bboxClip(
feature as Feature<LineString | MultiLineString>,
zoneToBBox(zone)
) as Feature<LineString | MultiLineString>;
return clipped.geometry.coordinates.length ? (clipped as T) : null;
}
const polygon = zoneToFeature(zone, true).geometry as Polygon;
if (feature.geometry.type === 'Point') {
return booleanPointInPolygon((feature as Feature<Point>).geometry.coordinates, polygon)
? tree
: null;
}
if (feature.geometry.type === 'MultiPoint') {
const res: Feature<MultiPoint> = {
...feature,
geometry: {
...feature.geometry,
coordinates: feature.geometry.coordinates.filter((position) =>
booleanPointInPolygon(position, polygon)
),
},
};
return res.geometry.coordinates.length ? (res as T) : null;
}
}
return tree;
}
/**
* This helpers takes an array of GeoJSON objects (as the editor data we use) and a zone, and
* returns a selection of all items in the given dataset intersecting with the given zone. If no
* zone is given, selects everything instead.
*/
export function selectInZone<T extends Feature>(data: Array<T>, zone?: Zone): T[] {
const items: T[] = [];
const zoneFeature = zone && zoneToFeature(zone, true);
data.forEach((geojson) => {
if (!zoneFeature || booleanIntersects(geojson, zoneFeature)) {
items.push(geojson);
}
});
return items;
}
/**
* This helpers takes a zone and a screen size and returns the smallest viewport that contains the
* zone.
*/
export function getZoneViewport(
zone: Zone,
viewport?: { width: number; height: number }
): ViewState {
const [minLng, minLat, maxLng, maxLat] = zoneToBBox(zone);
const vp = new WebMercatorViewport(viewport);
const { longitude, latitude, zoom } = vp.fitBounds(
[
[minLng, minLat],
[maxLng, maxLat],
],
{
padding: 40,
}
);
return {
latitude,
longitude,
zoom,
bearing: 0,
pitch: 0,
padding: { top: 0, left: 0, bottom: 0, right: 0 },
};
}
/**
* Given a list of points (as [lng, lat] point coordinates), returns the proper GeoJSON object to
* draw a line joining them
*/
export function getLineGeoJSON(points: Position[]): Feature {
return {
type: 'Feature',
properties: {},
geometry: {
type: 'LineString',
coordinates: points,
},
};
}
/**
* Give a list of lines or multilines and a specific position, returns the nearest point to that
* position on any of those lines.
*/
export function getNearestPoint(lines: Feature<LineString>[], coord: Coord): NearestPoint {
const nearestPoints: Feature<Point>[] = lines.map((line) => {
const point = nearestPointOnLine(line, coord, { units: 'meters' });
const angle = getAngle(
line.geometry.coordinates[point.properties.index as number],
line.geometry.coordinates[(point.properties.index as number) + 1]
);
return {
...point,
properties: {
...point.properties,
...line.properties,
angleAtPoint: angle,
},
};
});
return nearestPoint(coord, featureCollection(nearestPoints));
}
/**
* Given a Map MouseEvent, findthe nearest feature from the position of the mouse.
* @param e The MouseEvent
* @param opts Option object where
* - layerIds -> list of layer's id on which we search element
* - tolerance -> value in pixel to create the hitbox
*/
export function getMapMouseEventNearestFeature(
e: MapLayerMouseEvent,
opts?: { layersId?: string[]; tolerance: number; excludeOsm: boolean }
): { feature: MapboxGeoJSONFeature; nearest: number[]; distance: number } | null {
const layers = opts?.layersId;
const tolerance = opts?.tolerance || 15;
const excludeOsm = opts?.excludeOsm || true;
const { target: map, point } = e;
const coord = e.lngLat.toArray();
const features = map
.queryRenderedFeatures(
[
[point.x - tolerance / 2, point.y - tolerance / 2],
[point.x + tolerance / 2, point.y + tolerance / 2],
],
{ layers }
)
.filter((f) => (excludeOsm ? !f.layer.id.startsWith('osm') : true));
const result = head(
sortBy(
features.map((feature) => {
let distance = Infinity;
let nearestFeaturePoint: Feature<Point> | null = null;
switch (feature.geometry.type) {
case 'Point': {
nearestFeaturePoint = feature as Feature<Point>;
// we boost point, otherwise when a point is on line,
// it's too easy to find a point of line closest
distance = 0.7 * fnDistance(coord, nearestFeaturePoint.geometry.coordinates);
break;
}
case 'LineString': {
nearestFeaturePoint = nearestPointOnLine(feature.geometry, coord);
distance = fnDistance(coord, nearestFeaturePoint.geometry.coordinates);
break;
}
case 'MultiPoint': {
const points: FeatureCollection<Point> = {
type: 'FeatureCollection',
features: feature.geometry.coordinates.map((p) => ({
type: 'Feature',
geometry: {
type: 'Point',
coordinates: p,
},
properties: {},
})),
};
const pt = nearestPoint(coord, points);
distance = pt.properties.distanceToPoint;
nearestFeaturePoint = pt;
break;
}
case 'MultiLineString': {
const points: FeatureCollection<Point> = {
type: 'FeatureCollection',
features: feature.geometry.coordinates.map((lineString) =>
nearestPointOnLine({ type: 'LineString', coordinates: lineString }, coord)
),
};
const pt = nearestPoint(coord, points);
distance = pt.properties.distanceToPoint;
nearestFeaturePoint = pt;
break;
}
case 'Polygon': {
const points = fnExplode(feature.geometry);
const pt = nearestPoint(coord, points);
distance = pt.properties.distanceToPoint;
nearestFeaturePoint = pt;
break;
}
default:
distance = Infinity;
break;
}
return {
feature,
nearest: nearestFeaturePoint ? nearestFeaturePoint.geometry.coordinates : [0, 0],
distance,
};
}),
['distance']
)
);
if (!result) return null;
return result;
}