@maplibre/geojson-vt 6.2.0 → 6.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
 
2
2
  import {test, expect} from 'vitest';
3
- import {featureToGeoJSON, unprojectX, unprojectY} from './deconvert';
4
- import {projectX, projectY} from './convert';
3
+ import {featureToGeoJSON} from './deconvert';
4
+ import {mercatorWorldCoordinateHelper} from './world-coordinate-helper';
5
5
  import type {GeoJSONVTInternalFeature} from './definitions';
6
6
 
7
7
  test('project/unproject roundtrip retains precision', () => {
@@ -19,8 +19,8 @@ test('project/unproject roundtrip retains precision', () => {
19
19
  ];
20
20
 
21
21
  for (const {lng, lat} of coords) {
22
- expect(unprojectX(projectX(lng))).toBeCloseTo(lng, 10);
23
- expect(unprojectY(projectY(lat))).toBeCloseTo(lat, 10);
22
+ expect(mercatorWorldCoordinateHelper.unprojectX(mercatorWorldCoordinateHelper.projectX(lng))).toBeCloseTo(lng, 10);
23
+ expect(mercatorWorldCoordinateHelper.unprojectY(mercatorWorldCoordinateHelper.projectY(lat))).toBeCloseTo(lat, 10);
24
24
  }
25
25
  });
26
26
 
package/src/deconvert.ts CHANGED
@@ -1,12 +1,13 @@
1
+ import {mercatorWorldCoordinateHelper, type WorldCoordinateHelper} from './world-coordinate-helper';
1
2
  import type {GeoJSONVTInternalFeature} from './definitions';
2
3
 
3
4
  /**
4
5
  * Converts internal source features back to GeoJSON format.
5
6
  */
6
- export function convertToGeoJSON(source: GeoJSONVTInternalFeature[], worldCoordinates = false): GeoJSON.GeoJSON {
7
+ export function convertToGeoJSON(source: GeoJSONVTInternalFeature[], worldCoordinateHelper: WorldCoordinateHelper = mercatorWorldCoordinateHelper): GeoJSON.GeoJSON {
7
8
  const geojson: GeoJSON.GeoJSON = {
8
9
  type: 'FeatureCollection',
9
- features: source.map(feature => featureToGeoJSON(feature, worldCoordinates))
10
+ features: source.map(feature => featureToGeoJSON(feature, worldCoordinateHelper))
10
11
  };
11
12
 
12
13
  return geojson;
@@ -15,10 +16,10 @@ export function convertToGeoJSON(source: GeoJSONVTInternalFeature[], worldCoordi
15
16
  /**
16
17
  * Converts a single internal feature to GeoJSON format.
17
18
  */
18
- export function featureToGeoJSON(feature: GeoJSONVTInternalFeature, worldCoordinates = false): GeoJSON.Feature {
19
+ export function featureToGeoJSON(feature: GeoJSONVTInternalFeature, worldCoordinateHelper: WorldCoordinateHelper = mercatorWorldCoordinateHelper): GeoJSON.Feature {
19
20
  const geojsonFeature: GeoJSON.Feature = {
20
21
  type: 'Feature',
21
- geometry: geometryToGeoJSON(feature, worldCoordinates),
22
+ geometry: geometryToGeoJSON(feature, worldCoordinateHelper),
22
23
  properties: feature.tags
23
24
  };
24
25
  if (feature.id != null) {
@@ -31,68 +32,51 @@ export function featureToGeoJSON(feature: GeoJSONVTInternalFeature, worldCoordin
31
32
  /**
32
33
  * Converts a single internal feature geometry to GeoJSON format.
33
34
  */
34
- function geometryToGeoJSON(feature: GeoJSONVTInternalFeature, worldCoordinates: boolean): GeoJSON.Geometry {
35
+ function geometryToGeoJSON(feature: GeoJSONVTInternalFeature, worldCoordinateHelper: WorldCoordinateHelper): GeoJSON.Geometry {
35
36
  const {type, geometry} = feature;
36
37
 
37
38
  switch (type) {
38
39
  case 'Point':
39
40
  return {
40
41
  type: type,
41
- coordinates: unprojectPoint(geometry[0], geometry[1], worldCoordinates)
42
+ coordinates: unprojectPoint(geometry[0], geometry[1], worldCoordinateHelper)
42
43
  };
43
44
  case 'MultiPoint':
44
45
  return {
45
46
  type: type,
46
- coordinates: unprojectPoints(geometry, worldCoordinates)
47
+ coordinates: unprojectPoints(geometry, worldCoordinateHelper)
47
48
  };
48
49
  case 'LineString':
49
50
  return {
50
51
  type: type,
51
- coordinates: unprojectPoints(geometry.points, worldCoordinates)
52
+ coordinates: unprojectPoints(geometry.points, worldCoordinateHelper)
52
53
  };
53
54
  case 'MultiLineString':
54
55
  case 'Polygon':
55
56
  return {
56
57
  type: type,
57
- coordinates: geometry.map(ring => unprojectPoints(ring.points, worldCoordinates))
58
+ coordinates: geometry.map(ring => unprojectPoints(ring.points, worldCoordinateHelper))
58
59
  };
59
60
  case 'MultiPolygon':
60
61
  return {
61
62
  type: type,
62
63
  coordinates: geometry.map(polygon =>
63
- polygon.map(ring => unprojectPoints(ring.points, worldCoordinates))
64
+ polygon.map(ring => unprojectPoints(ring.points, worldCoordinateHelper))
64
65
  )
65
66
  };
66
67
  }
67
68
  }
68
69
 
69
- export function unprojectPoints(coords: number[] | Float64Array, worldCoordinates = false): GeoJSON.Position[] {
70
+ export function unprojectPoints(coords: number[] | Float64Array, worldCoordinateHelper: WorldCoordinateHelper = mercatorWorldCoordinateHelper): GeoJSON.Position[] {
70
71
  const result: GeoJSON.Position[] = [];
71
72
 
72
73
  for (let i = 0; i < coords.length; i += 3) {
73
- result.push(unprojectPoint(coords[i], coords[i + 1], worldCoordinates));
74
+ result.push(unprojectPoint(coords[i], coords[i + 1], worldCoordinateHelper));
74
75
  }
75
76
 
76
77
  return result;
77
78
  }
78
79
 
79
- function unprojectPoint(x: number, y: number, worldCoordinates: boolean): GeoJSON.Position {
80
- return [unprojectX(x, worldCoordinates), unprojectY(y, worldCoordinates)];
81
- }
82
-
83
- /**
84
- * Convert spherical mercator in [0..1] range to longitude, or keep a world coordinate as it is
85
- */
86
- export function unprojectX(x: number, worldCoordinates = false): number {
87
- if (worldCoordinates) return x;
88
- return (x - 0.5) * 360;
89
- }
90
-
91
- /**
92
- * Convert spherical mercator in [0..1] range to latitude, or keep a world coordinate as it is
93
- */
94
- export function unprojectY(y: number, worldCoordinates = false): number {
95
- if (worldCoordinates) return y;
96
- const y2 = (180 - y * 360) * Math.PI / 180;
97
- return 360 * Math.atan(Math.exp(y2)) / Math.PI - 90;
80
+ function unprojectPoint(x: number, y: number, worldCoordinateHelper: WorldCoordinateHelper): GeoJSON.Position {
81
+ return [worldCoordinateHelper.unprojectX(x), worldCoordinateHelper.unprojectY(y)];
98
82
  }
@@ -1,3 +1,9 @@
1
+ /**
2
+ * The space positions are given in, see `coordinates` in {@link GeoJSONVTOptions}.
3
+ * @experimental
4
+ */
5
+ export type GeoJSONVTCoordinatesType = 'lngLat' | 'unitSquare';
6
+
1
7
  export type GeoJSONVTOptions = {
2
8
  /**
3
9
  * Max zoom to preserve detail on
@@ -54,15 +60,23 @@ export type GeoJSONVTOptions = {
54
60
  */
55
61
  debug?: number;
56
62
  /**
57
- * Whether positions are world coordinates instead of lng/lat: x and y from 0 to 1 across the world square, y growing
58
- * downward, where web mercator would put a lng/lat. The world is then a square that ends at its edges, for data in a
59
- * world of its own such as a map projection's: positions are neither projected nor wrapped around or clamped,
60
- * features are cut at the tile buffer around the square, points outside it are left out of the clusters, `getTile`
61
- * returns `null` outside it, and `getData` and the cluster methods return world coordinates too.
63
+ * The space the positions are in. `'lngLat'` is longitude and latitude, which web mercator puts in the square from 0
64
+ * to 1 that tile 0/0/0 covers, with latitudes beyond ~85.05 degrees clamped onto its top and bottom. `'unitSquare'`
65
+ * is x and y in that square already, y growing downward, taken as they are, for data in another projection.
66
+ * `getData` and the cluster methods return positions in the same space.
62
67
  * @experimental
63
- * @default false
68
+ * @default 'lngLat'
64
69
  */
65
- worldCoordinates?: boolean;
70
+ coordinates?: GeoJSONVTCoordinatesType;
71
+ /**
72
+ * Whether the world wraps around the antimeridian. With `true`, features near the left or right edge are copied
73
+ * across it, and the tiles at either edge include what lies past it. With `false`, the world is the square and ends
74
+ * at its edges. Features are cut at the tile buffer around it, points outside it are left out of the clusters, and
75
+ * `getTile` returns `null` outside it. `geoJSONToTile` doesn't wrap unless this is `true`.
76
+ * @experimental
77
+ * @default true
78
+ */
79
+ wrap?: boolean;
66
80
  /**
67
81
  * Enable Supercluster for point features. Each position of a MultiPoint feature is clustered as a point of its own.
68
82
  * Other geometry types are left out.
@@ -70,15 +84,15 @@ export type GeoJSONVTOptions = {
70
84
  */
71
85
  cluster?: boolean;
72
86
  /**
73
- * Options for the Supercluster point clustering algorithm.
87
+ * Options for the Supercluster point clustering algorithm. `coordinates` and `wrap` come from the options above.
74
88
  * @see {@link SuperclusterOptions}
75
89
  */
76
- clusterOptions?: SuperclusterOptions;
90
+ clusterOptions?: Omit<SuperclusterOptions, 'coordinates' | 'wrap'>;
77
91
  };
78
92
 
79
93
  export type GeoJSONToTileOptions = GeoJSONVTOptions & {
80
94
  /**
81
- * Whether to wrap features around the antimeridian. Has no effect with `worldCoordinates`.
95
+ * Whether to wrap features around the antimeridian, see `wrap` in {@link GeoJSONVTOptions}.
82
96
  * @default false
83
97
  */
84
98
  wrap?: boolean;
@@ -275,4 +289,19 @@ export type SuperclusterOptions = {
275
289
  * @default props => props
276
290
  */
277
291
  map?: (props: GeoJSON.GeoJsonProperties) => Record<string, unknown>;
292
+ /**
293
+ * The space the points are in, see `coordinates` in {@link GeoJSONVTOptions}. The bounding box of `getClusters` is
294
+ * in the same space.
295
+ * @experimental
296
+ * @default 'lngLat'
297
+ */
298
+ coordinates?: GeoJSONVTCoordinatesType;
299
+ /**
300
+ * Whether the world wraps around the antimeridian, see `wrap` in {@link GeoJSONVTOptions}. With `false`, points
301
+ * outside the square are left out of the clusters, the tiles at an edge get no points from the opposite one, and
302
+ * `getTile` returns `null` outside the square.
303
+ * @experimental
304
+ * @default true
305
+ */
306
+ wrap?: boolean;
278
307
  };
package/src/difference.ts CHANGED
@@ -70,9 +70,10 @@ type HashedGeoJSONVTSourceDiff = {
70
70
  * @param source
71
71
  * @param dataDiff
72
72
  * @param options
73
+ * @param unlocated - the features without coordinates, by id, so that an update can give them some
73
74
  * @returns
74
75
  */
75
- export function applySourceDiff(source: GeoJSONVTInternalFeature[], dataDiff: GeoJSONVTSourceDiff, options: GeoJSONVTOptions): ApplySourceDiffResult {
76
+ export function applySourceDiff(source: GeoJSONVTInternalFeature[], dataDiff: GeoJSONVTSourceDiff, options: GeoJSONVTOptions, unlocated?: Map<string | number, GeoJSON.Feature>): ApplySourceDiffResult {
76
77
  // convert diff to sets/maps for o(1) lookups
77
78
  const diff = diffToHashed(dataDiff, options);
78
79
 
@@ -82,9 +83,12 @@ export function applySourceDiff(source: GeoJSONVTInternalFeature[], dataDiff: Ge
82
83
  if (diff.removeAll) {
83
84
  affected = source;
84
85
  source = [];
86
+ unlocated?.clear();
85
87
  }
86
88
 
87
89
  if (diff.remove.size || diff.add.size) {
90
+ for (const id of diff.remove) unlocated?.delete(id);
91
+
88
92
  const removeFeatures = [];
89
93
 
90
94
  // Collect features to remove (explicit removals + replacements via add)
@@ -101,7 +105,8 @@ export function applySourceDiff(source: GeoJSONVTInternalFeature[], dataDiff: Ge
101
105
  }
102
106
 
103
107
  if (diff.add.size) {
104
- let addFeatures = convertToInternal({type: 'FeatureCollection', features: Array.from(diff.add.values())}, options);
108
+ // added features keep their own ids, as generated ids are given to them before the diff is applied
109
+ let addFeatures = convertToInternal({type: 'FeatureCollection', features: Array.from(diff.add.values())}, {...options, generateId: false}, unlocated);
105
110
  addFeatures = wrap(addFeatures, options);
106
111
  affected = affected.concat(addFeatures);
107
112
  source = source.concat(addFeatures);
@@ -121,8 +126,14 @@ export function applySourceDiff(source: GeoJSONVTInternalFeature[], dataDiff: Ge
121
126
  }
122
127
  for (const [id, update] of diff.update) {
123
128
  const oldFeatures = oldFeaturesMap.get(id);
124
- if (!oldFeatures || oldFeatures.length === 0) continue;
125
- const updatedFeatures = getUpdatedFeatures(oldFeatures, update, options);
129
+ if (!oldFeatures || oldFeatures.length === 0) {
130
+ if (!unlocated?.has(id)) continue;
131
+ const locatedFeatures = getUpdatedUnlocatedFeatures(id, update, options, unlocated);
132
+ affected = affected.concat(locatedFeatures);
133
+ keepFeatures = keepFeatures.concat(locatedFeatures);
134
+ continue;
135
+ }
136
+ const updatedFeatures = getUpdatedFeatures(oldFeatures, update, options, unlocated);
126
137
 
127
138
  affected = affected.concat(oldFeatures, updatedFeatures);
128
139
  keepFeatures = keepFeatures.concat(updatedFeatures);
@@ -138,28 +149,18 @@ export function applySourceDiff(source: GeoJSONVTInternalFeature[], dataDiff: Ge
138
149
  * @param vtFeatures - the original features
139
150
  * @param update - the update object to apply
140
151
  * @param options - the options to use for the wrap method
152
+ * @param unlocated - the features without coordinates, by id, which a new geometry without coordinates adds the feature to
141
153
  * @returns Updated features. If geometry is updated, returns new feature(s) converted from geojson and wrapped, with the id the feature already has. If only properties are updated, returns feature(s) with tags updated.
142
154
  */
143
- function getUpdatedFeatures(vtFeatures: GeoJSONVTInternalFeature[], update: GeoJSONVTFeatureDiff, options: GeoJSONVTOptions): GeoJSONVTInternalFeature[] {
155
+ function getUpdatedFeatures(vtFeatures: GeoJSONVTInternalFeature[], update: GeoJSONVTFeatureDiff, options: GeoJSONVTOptions, unlocated?: Map<string | number, GeoJSON.Feature>): GeoJSONVTInternalFeature[] {
144
156
  const changeGeometry = !!update.newGeometry;
145
- const changeProps =
146
- update.removeAllProperties ||
147
- update.removeProperties?.length > 0 ||
148
- update.addOrUpdateProperties?.length > 0;
157
+ const changeProps = hasPropertyChanges(update);
149
158
 
150
159
  // if geometry changed, need to create a new geojson feature and convert to internal format
151
160
  if (changeGeometry) {
152
161
  const vtFeature = vtFeatures[0];
153
- const geojsonFeature = {
154
- type: 'Feature' as const,
155
- id: vtFeature.id,
156
- geometry: update.newGeometry,
157
- properties: changeProps ? applyPropertyUpdates(vtFeature.tags, update) : vtFeature.tags
158
- };
159
-
160
- let features = convertToInternal({type: 'FeatureCollection', features: [geojsonFeature]}, {...options, promoteId: undefined, generateId: false});
161
- features = wrap(features, options);
162
- return features;
162
+ const properties = changeProps ? applyPropertyUpdates(vtFeature.tags, update) : vtFeature.tags;
163
+ return convertNewGeometry(vtFeature.id, update.newGeometry, properties, options, unlocated);
163
164
  }
164
165
 
165
166
  if (changeProps) {
@@ -175,6 +176,35 @@ function getUpdatedFeatures(vtFeatures: GeoJSONVTInternalFeature[], update: GeoJ
175
176
  return vtFeatures;
176
177
  }
177
178
 
179
+ /**
180
+ * Gets the features an update gives a feature without coordinates: none, unless its new geometry has some.
181
+ * Its property changes apply either way.
182
+ */
183
+ function getUpdatedUnlocatedFeatures(id: string | number, update: GeoJSONVTFeatureDiff, options: GeoJSONVTOptions, unlocated: Map<string | number, GeoJSON.Feature>): GeoJSONVTInternalFeature[] {
184
+ const feature = unlocated.get(id);
185
+ const properties = hasPropertyChanges(update) ? applyPropertyUpdates(feature.properties, update) : feature.properties;
186
+ if (!update.newGeometry) {
187
+ unlocated.set(id, {...feature, properties});
188
+ return [];
189
+ }
190
+ return convertNewGeometry(id, update.newGeometry, properties, options, unlocated);
191
+ }
192
+
193
+ /**
194
+ * Converts the new geometry of a feature to internal format, keeping the id the feature already has
195
+ */
196
+ function convertNewGeometry(id: GeoJSONVTInternalFeature['id'], geometry: GeoJSON.Geometry, properties: GeoJSON.GeoJsonProperties, options: GeoJSONVTOptions, unlocated?: Map<string | number, GeoJSON.Feature>): GeoJSONVTInternalFeature[] {
197
+ const geojsonFeature = {type: 'Feature' as const, id, geometry, properties};
198
+ const features = convertToInternal({type: 'FeatureCollection', features: [geojsonFeature]}, {...options, promoteId: undefined, generateId: false}, unlocated);
199
+ return wrap(features, options);
200
+ }
201
+
202
+ function hasPropertyChanges(update: GeoJSONVTFeatureDiff): boolean {
203
+ return update.removeAllProperties ||
204
+ update.removeProperties?.length > 0 ||
205
+ update.addOrUpdateProperties?.length > 0;
206
+ }
207
+
178
208
  /**
179
209
  * helper to apply property updates from a diff update object to a properties object
180
210
  */
@@ -40,8 +40,8 @@ import type {GeoJSONToTileOptions, GeoJSONVTTile} from './definitions';
40
40
  */
41
41
 
42
42
  export function geoJSONToTile(data: GeoJSON.GeoJSON, z: number, x: number, y: number, options: GeoJSONToTileOptions = {}): GeoJSONVTTile {
43
- options = {...defaultOptions, ...options};
44
- const {wrap: shouldWrap = false, clip: shouldClip = false} = options;
43
+ options = {...defaultOptions, wrap: false, ...options};
44
+ const {wrap: shouldWrap, clip: shouldClip = false} = options;
45
45
 
46
46
  let features = convertToInternal(data, options);
47
47
  if (shouldWrap) {