forked from perliedman/query-overpass
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
86 lines (76 loc) · 2.77 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
var osmtogeojson = require('osmtogeojson'),
querystring = require('querystring'),
request = require('request'),
concat = require('concat-stream'),
JSONStream = require('JSONStream'),
xmldom = require('xmldom')
module.exports = function(query, cb, options) {
var contentType;
options = options || {};
var toGeoJSON = function(data) {
var geojson;
geojson = osmtogeojson(data, {
flatProperties: options.flatProperties || false
});
cb(undefined, geojson);
};
var handleXml = function (data) {
var parser = new xmldom.DOMParser();
var doc = parser.parseFromString(data);
toGeoJSON(doc);
}
var reqOptions = {
headers: {
'content-type': 'application/x-www-form-urlencoded'
},
body: querystring.stringify({ data: query })
};
var r;
if (!global.window) {
r = request.post(options.overpassUrl || 'https://overpass-api.de/api/interpreter', reqOptions);
r
.on('response', function(response) {
if (response.statusCode != 200) {
r.abort();
return cb({
message: 'Request failed: HTTP ' + response.statusCode,
statusCode: response.statusCode
});
}
contentType = response.headers['content-type'];
if (contentType.indexOf('json') >= 0) {
r.pipe(JSONStream.parse())
.on('data', toGeoJSON)
.on('error', cb);
} else if (contentType.indexOf('xml') >= 0) {
var body = '';
r.on('data', function (chunk) { body += chunk; })
.on('end', function() { handleXml(body); });
} else {
cb({
message: 'Unknown Content-Type "' + contentType + '" in response'
});
}
})
.on('error', cb);
} else {
r = request.post(options.overpassUrl || 'https://overpass-api.de/api/interpreter', reqOptions,
function (error, response, body) {
if (!error && response.statusCode === 200) {
toGeoJSON(JSON.parse(body));
} else if (error) {
cb(error);
} else if (response) {
cb({
message: 'Request failed: HTTP ' + response.statusCode,
statusCode: response.statusCode
});
} else {
cb({
message: 'Unknown error.',
});
}
});
}
return r;
};