-
Notifications
You must be signed in to change notification settings - Fork 12
/
getChangeset.js
106 lines (97 loc) · 2.85 KB
/
getChangeset.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
import adiffParser from 'osm-adiff-parser-saxjs';
import jsonParser from 'real-changesets-parser';
import { query } from './query';
import { config } from './config';
export function getChangeset(changesetID, options) {
return query(changesetID, options).then(data => {
const [changeset, options] = data;
if (options.enableRealChangesets) {
const url = `${config.S3_URL}${changesetID}.json`;
return fetch(url)
.then(r => {
if (r.ok) return r.json();
// Fallback to overpass
return Promise.reject();
})
.then(r => {
if (r.elements.length === 0) return Promise.reject();
const geojson = jsonParser(r);
const featureMap = getFeatureMap(geojson);
const ret = {
geojson: geojson,
featureMap: featureMap,
changeset: changeset
};
return ret;
})
.catch(() =>
fetchFromOverPass(changesetID, changeset, options.overpassBase)
);
} else {
return fetchFromOverPass(changesetID, changeset, options.overpassBase);
}
});
}
function fetchFromOverPass(changesetID, changeset, overpassBase) {
var data = getDataParam(changeset);
var bbox = getBboxParam(changeset.bbox);
var url = overpassBase + '?data=' + data + '&bbox=' + bbox;
return fetch(url, {
'Response-Type': 'application/osm3s+xml'
})
.then(r => r.text())
.then(response => {
return new Promise((res, rej) => {
adiffParser(response, null, (err, json) => {
if (err) {
return rej({
msg: 'Failed to parser adiff xml.',
error: err
});
}
var elements = Object.keys(json).reduce(
(result, item) => result.concat(json[item]),
[]
);
var geojson = jsonParser({
elements: elements
});
var featureMap = getFeatureMap(geojson);
var ret = {
geojson: geojson,
featureMap: featureMap,
changeset: changeset
};
return res(ret);
});
});
})
.catch(err =>
Promise.reject({
msg: 'Overpass query failed.',
error: err
})
);
}
function getDataParam(c) {
return (
'[out:xml][adiff:%22' +
c.from.toString() +
',%22,%22' +
c.to.toString() +
'%22];(node(bbox)(changed);way(bbox)(changed);relation(bbox)(changed););out%20meta%20geom(bbox);'
);
}
function getBboxParam(bbox) {
return [bbox.left, bbox.bottom, bbox.right, bbox.top].join(',');
}
function getFeatureMap(geojson) {
var features = geojson.features;
var featureMap = {};
for (var i = 0, len = features.length; i < len; i++) {
var id = features[i].properties.id;
featureMap[id] = featureMap[id] || [];
featureMap[id].push(features[i]);
}
return featureMap;
}