-
Notifications
You must be signed in to change notification settings - Fork 116
/
parse_osmxml.js
91 lines (88 loc) · 2.47 KB
/
parse_osmxml.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
/* converts OSM XML to OSM JSON using a fast streaming parser */
var htmlparser = require('htmlparser2');
var _ = require("./lodash.custom.js");
var json = {
"version": 0.6,
"elements": []
};
var buffer = {};
var p = new htmlparser.Parser({
onopentag: function(name, attr) {
switch (name) {
case "node":
case "way":
case "relation":
buffer = {
type: name,
tags: {}
}
_.merge(buffer, attr);
if (name === "way") {
buffer.nodes = [];
buffer.geometry = [];
}
if (name === "relation") {
buffer.members = [];
buffer.nodes = [];
buffer.geometry = [];
}
break;
case "tag":
buffer.tags[attr.k] = attr.v;
break;
case "nd":
buffer.nodes.push(attr.ref);
if (attr.lat) {
buffer.geometry.push({
lat: attr.lat,
lon: attr.lon
});
} else {
buffer.geometry.push(null);
}
break;
case "member":
buffer.members.push(attr);
break;
case "center":
buffer.center = {
lat: attr.lat,
lon: attr.lon
};
break;
case "bounds":
buffer.bounds = {
minlat: attr.minlat,
minlon: attr.minlon,
maxlat: attr.maxlat,
maxlon: attr.maxlon
};
}
},
ontext: function(text) {
},
onclosetag: function(name) {
if (name === "node" || name === "way" || name === "relation" || name === "area") {
// remove empty geometry or nodes arrays
if (buffer.geometry && buffer.geometry.every(function(g) {return g===null;}))
delete buffer.geometry;
if (name === "relation")
delete buffer.nodes;
json.elements.push(buffer);
}
if (name === "member") {
if (buffer.geometry) {
buffer.members[buffer.members.length-1].geometry = buffer.geometry;
buffer.geometry = [];
}
}
}
}, {
decodeEntities: true,
xmlMode: true
});
p.parseFromString = function(xml_str) { p.write(xml_str); p.end(); return json; }
p.getJSON = function() {
return json;
}
module.exports = p;