This repository was archived by the owner on Jan 9, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathgeojsonUtil.js
313 lines (287 loc) · 9.4 KB
/
geojsonUtil.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
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
import _ from 'underscore';
import * as d3 from 'd3';
/* globals moment */
import colorbrewer from 'colorbrewer';
window.colorbrewer = colorbrewer;
const geojsonUtil = {};
/**
* Merge a new value into an accumulation object.
* The result depends on the value type:
*
* 1. string: stores a values object that maps
* the values encountered to the total
* number of occurences.
*
* 2. number: stores the minimum and maximum values
* encountered
*/
geojsonUtil.merge = function merge(value, accumulated) {
accumulated = accumulated || { count: 0 };
accumulated.count += 1;
switch (typeof value) {
case 'string':
accumulated.values = accumulated.values || {};
accumulated.values[value] = (accumulated.values[value] || 0) + 1;
break;
case 'number':
if (isFinite(value)) {
accumulated.nFinite = (accumulated.nFinite || 0) + 1;
accumulated.min = Math.min(
accumulated.min !== undefined ? accumulated.min : Number.POSITIVE_INFINITY,
value
);
accumulated.max = Math.max(
accumulated.max !== undefined ? accumulated.max : Number.NEGATIVE_INFINITY,
value
);
accumulated.sum = (accumulated.sum || 0) + value;
accumulated.sumsq = (accumulated.sumsq || 0) + value * value;
}
break;
}
return accumulated;
};
/**
* A list of property keys that are ignored when generating
* geojson summaries.
*/
geojsonUtil.ignored_properties = [
'cluster',
'clusterDistance',
'clusterFillColor',
'clusterStrokeColor',
'clusterRadius',
'fill',
'fillColor',
'fillOpacity',
'radius',
'stroke',
'strokeColor',
'strokeWidth',
'strokeOpacity',
'fillColorKey',
'strokeColorKey'
].sort();
/**
* Accumulate property values into a summary object. The
* output object will have keys encountered in the feature
* array mapped to an object that summarizes the values
* encountered.
*
* @param {object[]} features An array of "property" objects
* @returns {object}
*/
geojsonUtil.accumulate = function accumulate(features) {
var feature, i, accumulated = {}, key;
for (i = 0; i < features.length; i += 1) {
feature = features[i];
for (key in feature) {
if (feature.hasOwnProperty(key) && !_.contains(geojsonUtil.ignored_properties, key)) {
accumulated[key] = geojsonUtil.merge(feature[key], accumulated[key]);
}
}
}
return accumulated;
};
/**
* Normalize a geojson object turning geometries into features and
* returning a feature collection. The returned feature collection
* is processed to provide a summary object containing accumulated
* property statistics that can be used to generate numeric/color
* scales for visualization.
*/
geojsonUtil.normalize = function normalize(geojson) { // eslint-disable-line complexity
var normalized;
if (_.isString(geojson)) {
try {
geojson = JSON.parse(geojson);
} catch (e) {
}
}
/* Check if this is a geojson-timeseries. If so, normalize each each
* entry. The root contains the first geojson entry and a summary that
* combines all of the entries summaries. */
if (_.isArray(geojson) && geojson[0].geojson && geojson[0].time) {
_.each(geojson, function (entry) {
var norm = geojsonUtil.normalize(entry.geojson);
if (norm) {
if (!normalized) {
normalized = $.extend({ series: [] }, norm);
normalized.summary = {};
}
var label = '' + (entry.label || (entry.time ? moment(entry.time).format('L LTS') : null) || ('Frame ' + (normalized.series.length + 1)));
var time = moment.utc(entry.time);
normalized.series.push({ time: time, geojson: norm, label: label });
}
});
normalized.summary = geojsonUtil.accumulate(
_.flatten(normalized.series.map((series) => series.geojson.features))
.map((feature) => feature.properties)
);
return normalized;
}
switch (geojson.type) {
case 'FeatureCollection':
normalized = geojson;
break;
case 'Feature':
normalized = {
type: 'FeatureCollection',
features: [geojson]
};
break;
case 'GeometryCollection':
normalized = {
type: 'FeatureCollection',
features: geojson.geometries.map(function (g) {
return {
type: 'Feature',
geometry: g,
properties: {}
};
})
};
break;
case 'Point':
case 'LineString':
case 'Polygon':
case 'MultiPoint':
case 'MultiLineString':
case 'MultiPolygon':
normalized = {
type: 'FeatureCollection',
features: [{
type: 'Feature',
geometry: geojson,
properties: {}
}]
};
break;
default:
throw new Error('Invalid json type');
}
// generate property summary
normalized.summary = geojsonUtil.accumulate(
normalized.features.map(function (f) { return f.properties; })
);
return normalized;
};
/**
* Set style properties in the geojson according to the
* `visProperties` mapping. This will loop through all
* of the contained features and append "property"
* key -> value pairs for each vis property.
*
* This method mutates the geojson object.
*
* @note assumes the geojson object is normalized
*/
geojsonUtil.style = function style(geojson, visProperties) {
visProperties = visProperties || {};
_.each(geojson.features || [], function (feature) {
var properties = feature.properties || {};
var geometry = feature.geometry || {};
var style = {};
switch (geometry.type) {
case 'Point':
case 'MultiPoint':
style = visProperties.point || {};
break;
case 'LineString':
case 'MultiLineString':
style = visProperties.line || {};
break;
case 'Polygon':
case 'MultiPolygon':
style = visProperties.polygon || {};
break;
}
_.each(style, function (scale, key) {
if (_.isFunction(scale)) {
properties[key] = scale(properties, key, geometry);
} else {
properties[key] = scale;
}
});
feature.properties = properties;
});
return geojson;
};
/**
* Generate a d3-like scale function out of a colorbrewer
* ramp name and a geojson summary object.
*
* @param {string} ramp
* @param {object} summary
* @param {Boolean} logFlag
* @returns {function}
*/
geojsonUtil.colorScale = function colorScale(
ramp, summary,
logFlag, quantileFlag, clampingFlag, minClamp, maxClamp,
data) {
var scale, s, colors, n, indices;
colors = colorbrewer[ramp];
// for an invalid ramp, just return black
if (!colors) {
return function () { // eslint-disable-line underscore/prefer-constant
return '#ffffff';
};
}
indices = _.keys(colors).map(function (v) {
return parseInt(v, 10);
});
if (_.isObject(summary.values)) { // categorical
n = _.sortedIndex(indices, _.size(summary.values));
n = Math.min(n, indices.length - 1);
scale = d3.scale.ordinal()
.domain(_.keys(summary.values))
.range(colors[indices[n]]);
} else { // continuous
n = indices.length - 1;
// handle the case when all values are the same
if (summary.min >= summary.max) {
summary.max = summary.min + 1;
}
if (logFlag && summary.min > 0) {
s = d3.scale.quantize()
.domain([Math.log(summary.min), Math.log(summary.max)])
.range(colors[indices[n]]);
scale = function (val) {
return s(Math.log(val));
};
} else if (quantileFlag) {
scale = d3.scale.quantile()
.domain(data)
.range(colors[indices[n]]);
} else {
// linear scaling
if (clampingFlag) {
scale = d3.scale.quantize()
.domain([minClamp, maxClamp])
.range(colors[indices[n]]);
} else {
scale = d3.scale.quantize()
.domain([summary.min, summary.max])
.range(colors[indices[n]]);
}
}
}
return scale;
};
/**
* Return an array of the indicated type from a geojson object.
* If no types are given, return all features.
*/
geojsonUtil.getFeatures = function getFeatures(data) {
var types = _.rest(arguments, 1).sort();
var all = (data || {}).features || [];
if (!types.length) {
return all;
}
return _.filter(all, function (f) {
var geom = f.geometry || {};
return _.indexOf(types, geom.type, true) >= 0;
});
};
export default geojsonUtil;