-
Notifications
You must be signed in to change notification settings - Fork 290
/
geojson.js
276 lines (234 loc) · 9.67 KB
/
geojson.js
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
import log from '../utils/log';
import DataSource, {NetworkSource, NetworkTileSource} from './data_source';
import {decodeMultiPolygon} from './mvt';
import Geo from '../geo';
// For tiling GeoJSON client-side
import geojsonvt from 'geojson-vt';
/**
GeoJSON standalone (non-tiled) source
Uses geojson-vt split into tiles client-side
*/
export class GeoJSONSource extends NetworkSource {
constructor(source, sources) {
super(source, sources);
this.load_data = null;
this.tile_indexes = {}; // geojson-vt tile indices, by layer name
this.max_zoom = Math.max(this.max_zoom || 0, 15); // TODO: max zoom < 15 causes artifacts/no-draw at 20, investigate
this.setTileSize(512); // auto-tile to 512px tiles for better labelling
this.pad_scale = 0; // we don't want padding on auto-tiled sources
}
_load(dest) {
if (!this.load_data) {
this.load_data = super._load({ source_data: { layers: {} } }).then(data => {
// Warn and continue on data source error
if (data.source_data.error) {
log('warn', `data source load error(s) for source '${this.name}', URL '${this.url}': ${data.source_data.error}`);
}
let layers = data.source_data.layers;
for (let layer_name in layers) {
this.tile_indexes[layer_name] = geojsonvt(layers[layer_name], {
maxZoom: this.max_zoom, // max zoom to preserve detail on
tolerance: 1.5, // simplification tolerance (higher means simpler) NB: half the default to accomodate 512px tiles
extent: Geo.tile_scale, // tile extent (both width and height)
buffer: 0.0001 // tile buffer on each side
});
}
this.loaded = true;
return data;
});
}
return this.load_data.then(() => {
for (let layer_name in this.tile_indexes) {
dest.source_data.layers[layer_name] = this.getTileFeatures(dest, layer_name);
}
return dest;
});
}
getTileFeatures(tile, layer_name) {
let coords = Geo.wrapTile(tile.coords, { x: true });
// request a particular tile
let t = this.tile_indexes[layer_name].getTile(coords.z, coords.x, coords.y);
// Convert from MVT-style JSON struct to GeoJSON
let collection;
if (t && t.features) {
collection = {
type: 'FeatureCollection',
features: []
};
for (let i=0; i < t.features.length; i++) {
const feature = t.features[i];
// GeoJSON feature
let f = {
type: 'Feature',
geometry: {},
properties: feature.tags
};
if (feature.type === 1) {
f.geometry.coordinates = feature.geometry.map(coord => [coord[0], coord[1]]);
f.geometry.type = 'MultiPoint';
}
else if (feature.type === 2 || feature.type === 3) {
f.geometry.coordinates = feature.geometry.map(ring =>
ring.map(coord => [coord[0], coord[1]])
);
if (feature.type === 2) {
f.geometry.type = 'MultiLineString';
}
else {
f.geometry = decodeMultiPolygon(f.geometry); // un-flatten rings
if (f.geometry == null) { // skip polys that couldn't be decoded (e.g. degenerate)
continue;
}
}
}
else {
continue;
}
collection.features.push(f);
}
}
return collection;
}
formatUrl (dest) {
return this.url;
}
parseSourceData (tile, source, response) {
let data = typeof response === 'string' ? JSON.parse(response) : response;
let layers = this.getLayers(data);
source.layers = this.preprocessLayers(layers);
}
preprocessLayers (layers){
for (let key in layers) {
let layer = layers[key];
layer.features = this.preprocessFeatures(layer.features);
}
// Apply optional data transform
if (typeof this.transform === 'function') {
if (Object.keys(layers).length === 1 && layers._default) {
layers._default = this.transform(layers._default, this.extra_data); // single-layer
}
else {
layers = this.transform(layers, this.extra_data); // multiple layers
}
}
return layers;
}
// Preprocess features. Currently used to add a new "centroid" feature for polygon labeling
preprocessFeatures (features) {
// Remove features without geometry (which is valid GeoJSON)
features = features.filter(f => f.geometry != null);
// Define centroids for polygons for centroid label placement
// Avoids redundant label placement for each generated tile at higher zoom levels
if (this.config.generate_label_centroids){
let features_centroid = [];
let centroid_properties = {"label_placement" : true};
features.forEach(feature => {
let coordinates, centroid_feature;
switch (feature.geometry.type) {
case 'Polygon':
coordinates = feature.geometry.coordinates;
centroid_feature = getCentroidFeatureForPolygon(coordinates, feature.properties, centroid_properties);
features_centroid.push(centroid_feature);
break;
case 'MultiPolygon':
// Add centroid feature for largest polygon
coordinates = feature.geometry.coordinates;
let max_area = -Infinity;
let max_area_index = 0;
for (let index = 0; index < coordinates.length; index++) {
let area = Geo.polygonArea(coordinates[index]);
if (area > max_area) {
max_area = area;
max_area_index = index;
}
}
centroid_feature = getCentroidFeatureForPolygon(coordinates[max_area_index], feature.properties, centroid_properties);
features_centroid.push(centroid_feature);
break;
}
});
// append centroid features to features array
features_centroid = features_centroid.filter(x => x); // remove null features
Array.prototype.push.apply(features, features_centroid);
}
return features;
}
// Detect single or multiple layers in returned data
getLayers (data) {
if (data.type === 'Feature') {
return {
_default: {
type: 'FeatureCollection',
features: [data]
}
};
}
else if (data.type === 'FeatureCollection') {
return {
_default: data
};
}
else {
return data;
}
}
}
/**
GeoJSON vector tiles
@class GeoJSONTileSource
*/
export class GeoJSONTileSource extends NetworkTileSource {
constructor(source, sources) {
super(source, sources);
// Check for URL tile pattern, if not found, treat as standalone GeoJSON/TopoJSON object
if (!this.urlHasTilePattern(this.url)) {
// Check instance type from parent class
if (source.type === 'GeoJSON') {
// Replace instance type
return new GeoJSONSource(source);
}
else {
// Pass back to parent class to instantiate
return null;
}
}
return this;
}
parseSourceData (tile, source, response) {
let data = typeof response === 'string' ? JSON.parse(response) : response;
this.prepareGeoJSON(data, tile, source);
}
prepareGeoJSON (data, tile, source) {
// Apply optional data transform
if (typeof this.transform === 'function') {
data = this.transform(data, this.extra_data);
}
source.layers = GeoJSONSource.prototype.getLayers(data);
// A "synthetic" tile that adjusts the tile min anchor to account for tile longitude wrapping
let anchor = {
coords: tile.coords,
min: Geo.metersForTile(Geo.wrapTile(tile.coords, { x: true }))
};
DataSource.projectData(source); // mercator projection
DataSource.scaleData(source, anchor); // re-scale from meters to local tile coords
}
}
DataSource.register(GeoJSONTileSource, 'GeoJSON'); // prefered shorter name
// Helper function to create centroid point feature from polygon coordinates and provided feature meta-data
function getCentroidFeatureForPolygon (coordinates, properties, newProperties) {
let centroid = Geo.centroid(coordinates);
if (!centroid) {
return;
}
// clone properties and mixix newProperties
let centroid_properties = {};
Object.assign(centroid_properties, properties, newProperties);
return {
type: "Feature",
properties: centroid_properties,
geometry: {
type: "Point",
coordinates: centroid
}
};
}