forked from maplibre/maplibre-gl-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgeojson_source.ts
433 lines (390 loc) · 15.2 KB
/
geojson_source.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
import {Event, ErrorEvent, Evented} from '../util/evented';
import {extend, warnOnce} from '../util/util';
import {EXTENT} from '../data/extent';
import {ResourceType} from '../util/request_manager';
import {browser} from '../util/browser';
import type {Source} from './source';
import type {Map} from '../ui/map';
import type {Dispatcher} from '../util/dispatcher';
import type {Tile} from './tile';
import type {Actor} from '../util/actor';
import type {GeoJSONSourceSpecification, PromoteIdSpecification} from '@maplibre/maplibre-gl-style-spec';
import type {GeoJSONSourceDiff} from './geojson_source_diff';
import type {GeoJSONWorkerOptions, LoadGeoJSONParameters} from './geojson_worker_source';
import {WorkerTileParameters} from './worker_source';
import {MessageType} from '../util/actor_messages';
/**
* Options object for GeoJSONSource.
*/
export type GeoJSONSourceOptions = GeoJSONSourceSpecification & {
workerOptions?: GeoJSONWorkerOptions;
collectResourceTiming?: boolean;
data: GeoJSON.GeoJSON | string;
}
export type GeoJSONSourceInternalOptions = {
data?: GeoJSON.GeoJSON | string | undefined;
cluster?: boolean;
clusterMaxZoom?: number;
clusterRadius?: number;
clusterMinPoints?: number;
generateId?: boolean;
}
/**
* The cluster options to set
*/
export type SetClusterOptions = {
/**
* Whether or not to cluster
*/
cluster?: boolean;
/**
* The cluster's max zoom
*/
clusterMaxZoom?: number;
/**
* The cluster's radius
*/
clusterRadius?: number;
}
/**
* A source containing GeoJSON.
* (See the [Style Specification](https://maplibre.org/maplibre-style-spec/#sources-geojson) for detailed documentation of options.)
*
* @group Sources
*
* @example
* ```ts
* map.addSource('some id', {
* type: 'geojson',
* data: 'https://d2ad6b4ur7yvpq.cloudfront.net/naturalearth-3.3.0/ne_10m_ports.geojson'
* });
* ```
*
* @example
* ```ts
* map.addSource('some id', {
* type: 'geojson',
* data: {
* "type": "FeatureCollection",
* "features": [{
* "type": "Feature",
* "properties": {},
* "geometry": {
* "type": "Point",
* "coordinates": [
* -76.53063297271729,
* 39.18174077994108
* ]
* }
* }]
* }
* });
* ```
*
* @example
* ```ts
* map.getSource('some id').setData({
* "type": "FeatureCollection",
* "features": [{
* "type": "Feature",
* "properties": { "name": "Null Island" },
* "geometry": {
* "type": "Point",
* "coordinates": [ 0, 0 ]
* }
* }]
* });
* ```
* @see [Draw GeoJSON points](https://maplibre.org/maplibre-gl-js/docs/examples/geojson-markers/)
* @see [Add a GeoJSON line](https://maplibre.org/maplibre-gl-js/docs/examples/geojson-line/)
* @see [Create a heatmap from points](https://maplibre.org/maplibre-gl-js/docs/examples/heatmap-layer/)
* @see [Create and style clusters](https://maplibre.org/maplibre-gl-js/docs/examples/cluster/)
*/
export class GeoJSONSource extends Evented implements Source {
type: 'geojson';
id: string;
minzoom: number;
maxzoom: number;
tileSize: number;
attribution: string;
promoteId: PromoteIdSpecification;
isTileClipped: boolean;
reparseOverscaled: boolean;
_data: GeoJSON.GeoJSON | string | undefined;
_options: GeoJSONSourceInternalOptions;
workerOptions: GeoJSONWorkerOptions;
map: Map;
actor: Actor;
_pendingLoads: number;
_collectResourceTiming: boolean;
_removed: boolean;
/** @internal */
constructor(id: string, options: GeoJSONSourceOptions, dispatcher: Dispatcher, eventedParent: Evented) {
super();
this.id = id;
// `type` is a property rather than a constant to make it easy for 3rd
// parties to use GeoJSONSource to build their own source types.
this.type = 'geojson';
this.minzoom = 0;
this.maxzoom = 18;
this.tileSize = 512;
this.isTileClipped = true;
this.reparseOverscaled = true;
this._removed = false;
this._pendingLoads = 0;
this.actor = dispatcher.getActor();
this.setEventedParent(eventedParent);
this._data = (options.data as any);
this._options = extend({}, options);
this._collectResourceTiming = options.collectResourceTiming;
if (options.maxzoom !== undefined) this.maxzoom = options.maxzoom;
if (options.type) this.type = options.type;
if (options.attribution) this.attribution = options.attribution;
this.promoteId = options.promoteId;
const scale = EXTENT / this.tileSize;
if (options.clusterMaxZoom !== undefined && this.maxzoom <= options.clusterMaxZoom) {
warnOnce(`The maxzoom value "${this.maxzoom}" is expected to be greater than the clusterMaxZoom value "${options.clusterMaxZoom}".`);
}
// sent to the worker, along with `url: ...` or `data: literal geojson`,
// so that it can load/parse/index the geojson data
// extending with `options.workerOptions` helps to make it easy for
// third-party sources to hack/reuse GeoJSONSource.
this.workerOptions = extend({
source: this.id,
cluster: options.cluster || false,
geojsonVtOptions: {
buffer: (options.buffer !== undefined ? options.buffer : 128) * scale,
tolerance: (options.tolerance !== undefined ? options.tolerance : 0.375) * scale,
extent: EXTENT,
maxZoom: this.maxzoom,
lineMetrics: options.lineMetrics || false,
generateId: options.generateId || false
},
superclusterOptions: {
maxZoom: options.clusterMaxZoom !== undefined ? options.clusterMaxZoom : this.maxzoom - 1,
minPoints: Math.max(2, options.clusterMinPoints || 2),
extent: EXTENT,
radius: (options.clusterRadius || 50) * scale,
log: false,
generateId: options.generateId || false
},
clusterProperties: options.clusterProperties,
filter: options.filter
}, options.workerOptions);
// send the promoteId to the worker to have more flexible updates, but only if it is a string
if (typeof this.promoteId === 'string') {
this.workerOptions.promoteId = this.promoteId;
}
}
async load() {
await this._updateWorkerData();
}
onAdd(map: Map) {
this.map = map;
this.load();
}
/**
* Sets the GeoJSON data and re-renders the map.
*
* @param data - A GeoJSON data object or a URL to one. The latter is preferable in the case of large GeoJSON files.
*/
setData(data: GeoJSON.GeoJSON | string): this {
this._data = data;
this._updateWorkerData();
return this;
}
/**
* Updates the source's GeoJSON, and re-renders the map.
*
* For sources with lots of features, this method can be used to make updates more quickly.
*
* This approach requires unique IDs for every feature in the source. The IDs can either be specified on the feature,
* or by using the promoteId option to specify which property should be used as the ID.
*
* It is an error to call updateData on a source that did not have unique IDs for each of its features already.
*
* Updates are applied on a best-effort basis, updating an ID that does not exist will not result in an error.
*
* @param diff - The changes that need to be applied.
*/
updateData(diff: GeoJSONSourceDiff): this {
this._updateWorkerData(diff);
return this;
}
/**
* Allows to get the source's actual GeoJSON data.
*
* @returns a promise which resolves to the source's actual GeoJSON data
*/
async getData(): Promise<GeoJSON.GeoJSON> {
const options: LoadGeoJSONParameters = extend({type: this.type}, this.workerOptions);
return this.actor.sendAsync({type: MessageType.getData, data: options});
}
/**
* To disable/enable clustering on the source options
* @param options - The options to set
* @example
* ```ts
* map.getSource('some id').setClusterOptions({cluster: false});
* map.getSource('some id').setClusterOptions({cluster: false, clusterRadius: 50, clusterMaxZoom: 14});
* ```
*/
setClusterOptions(options: SetClusterOptions): this {
this.workerOptions.cluster = options.cluster;
if (options) {
if (options.clusterRadius !== undefined) this.workerOptions.superclusterOptions.radius = options.clusterRadius;
if (options.clusterMaxZoom !== undefined) this.workerOptions.superclusterOptions.maxZoom = options.clusterMaxZoom;
}
this._updateWorkerData();
return this;
}
/**
* For clustered sources, fetches the zoom at which the given cluster expands.
*
* @param clusterId - The value of the cluster's `cluster_id` property.
* @returns a promise that is resolved with the zoom number
*/
getClusterExpansionZoom(clusterId: number): Promise<number> {
return this.actor.sendAsync({type: MessageType.getClusterExpansionZoom, data: {type: this.type, clusterId, source: this.id}});
}
/**
* For clustered sources, fetches the children of the given cluster on the next zoom level (as an array of GeoJSON features).
*
* @param clusterId - The value of the cluster's `cluster_id` property.
* @returns a promise that is resolved when the features are retrieved
*/
getClusterChildren(clusterId: number): Promise<Array<GeoJSON.Feature>> {
return this.actor.sendAsync({type: MessageType.getClusterChildren, data: {type: this.type, clusterId, source: this.id}});
}
/**
* For clustered sources, fetches the original points that belong to the cluster (as an array of GeoJSON features).
*
* @param clusterId - The value of the cluster's `cluster_id` property.
* @param limit - The maximum number of features to return.
* @param offset - The number of features to skip (e.g. for pagination).
* @returns a promise that is resolved when the features are retrieved
* @example
* Retrieve cluster leaves on click
* ```ts
* map.on('click', 'clusters', (e) => {
* let features = map.queryRenderedFeatures(e.point, {
* layers: ['clusters']
* });
*
* let clusterId = features[0].properties.cluster_id;
* let pointCount = features[0].properties.point_count;
* let clusterSource = map.getSource('clusters');
*
* const features = await clusterSource.getClusterLeaves(clusterId, pointCount);
* // Print cluster leaves in the console
* console.log('Cluster leaves:', features);
* });
* ```
*/
getClusterLeaves(clusterId: number, limit: number, offset: number): Promise<Array<GeoJSON.Feature>> {
return this.actor.sendAsync({type: MessageType.getClusterLeaves, data: {
type: this.type,
source: this.id,
clusterId,
limit,
offset
}});
}
/**
* Responsible for invoking WorkerSource's geojson.loadData target, which
* handles loading the geojson data and preparing to serve it up as tiles,
* using geojson-vt or supercluster as appropriate.
* @param diff - the diff object
*/
async _updateWorkerData(diff?: GeoJSONSourceDiff) {
const options: LoadGeoJSONParameters = extend({type: this.type}, this.workerOptions);
if (diff) {
options.dataDiff = diff;
} else if (typeof this._data === 'string') {
options.request = this.map._requestManager.transformRequest(browser.resolveURL(this._data as string), ResourceType.Source);
options.request.collectResourceTiming = this._collectResourceTiming;
} else {
options.data = JSON.stringify(this._data);
}
this._pendingLoads++;
this.fire(new Event('dataloading', {dataType: 'source'}));
try {
const result = await this.actor.sendAsync({type: MessageType.loadData, data: options});
this._pendingLoads--;
if (this._removed || result.abandoned) {
this.fire(new Event('dataabort', {dataType: 'source'}));
return;
}
let resourceTiming: PerformanceResourceTiming[] = null;
if (result.resourceTiming && result.resourceTiming[this.id]) {
resourceTiming = result.resourceTiming[this.id].slice(0);
}
const data: any = {dataType: 'source'};
if (this._collectResourceTiming && resourceTiming && resourceTiming.length > 0) {
extend(data, {resourceTiming});
}
// although GeoJSON sources contain no metadata, we fire this event to let the SourceCache
// know its ok to start requesting tiles.
this.fire(new Event('data', {...data, sourceDataType: 'metadata'}));
this.fire(new Event('data', {...data, sourceDataType: 'content'}));
} catch (err) {
this._pendingLoads--;
if (this._removed) {
this.fire(new Event('dataabort', {dataType: 'source'}));
return;
}
this.fire(new ErrorEvent(err));
}
}
loaded(): boolean {
return this._pendingLoads === 0;
}
async loadTile(tile: Tile): Promise<void> {
const message = !tile.actor ? MessageType.loadTile : MessageType.reloadTile;
tile.actor = this.actor;
const params: WorkerTileParameters = {
type: this.type,
uid: tile.uid,
tileID: tile.tileID,
zoom: tile.tileID.overscaledZ,
maxZoom: this.maxzoom,
tileSize: this.tileSize,
source: this.id,
pixelRatio: this.map.getPixelRatio(),
showCollisionBoxes: this.map.showCollisionBoxes,
promoteId: this.promoteId,
subdivisionGranularity: this.map.style.projection.subdivisionGranularity
};
tile.abortController = new AbortController();
const data = await this.actor.sendAsync({type: message, data: params}, tile.abortController);
delete tile.abortController;
tile.unloadVectorData();
if (!tile.aborted) {
tile.loadVectorData(data, this.map.painter, message === MessageType.reloadTile);
}
}
async abortTile(tile: Tile) {
if (tile.abortController) {
tile.abortController.abort();
delete tile.abortController;
}
tile.aborted = true;
}
async unloadTile(tile: Tile) {
tile.unloadVectorData();
await this.actor.sendAsync({type: MessageType.removeTile, data: {uid: tile.uid, type: this.type, source: this.id}});
}
onRemove() {
this._removed = true;
this.actor.sendAsync({type: MessageType.removeSource, data: {type: this.type, source: this.id}});
}
serialize(): GeoJSONSourceSpecification {
return extend({}, this._options, {
type: this.type,
data: this._data
});
}
hasTransition() {
return false;
}
}