forked from mapbox/geojson-normalize
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
70 lines (66 loc) · 1.8 KB
/
index.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
module.exports = normalize;
var types = {
Point: 'geometry',
MultiPoint: 'geometry',
LineString: 'geometry',
MultiLineString: 'geometry',
Polygon: 'geometry',
MultiPolygon: 'geometry',
GeometryCollection: 'geometry',
Feature: 'feature',
FeatureCollection: 'featurecollection'
};
/**
* Converts strings to Floats.
*
* @param {array} coordinates coordinates
*/
function numberify(coordinates) {
return coordinates.map(function(coord) {
if (coord.constructor === Array) {
return coord.map(function(c) {
if (c.constructor === Array) {
return c.map(parseFloat);
} else {
return parseFloat(c);
}
});
} else {
return parseFloat(coord);
}
});
}
/**
* Normalize a GeoJSON feature into a FeatureCollection.
*
* @param {object} gj geojson data
* @returns {object} normalized geojson data
*/
function normalize(gj) {
if (!gj || !gj.type) return null;
var type = types[gj.type];
if (!type) return null;
if (type === 'geometry') {
gj.coordinates = numberify(gj.coordinates);
return {
type: 'FeatureCollection',
features: [{
type: 'Feature',
properties: {},
geometry: gj
}]
};
} else if (type === 'feature') {
gj.geometry.coordinates = numberify(gj.geometry.coordinates);
return {
type: 'FeatureCollection',
features: [gj]
};
} else if (type === 'featurecollection') {
gj.features = gj.features.map(function(feature) {
feature.geometry.coordinates = numberify(feature.geometry.coordinates);
return feature;
});
return gj;
}
}