forked from PeWu/osm-history
-
Notifications
You must be signed in to change notification settings - Fork 0
/
osm-service.js
72 lines (60 loc) · 1.62 KB
/
osm-service.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
/** Base URL for accessing OSM API. */
API_URL_BASE = 'https://api.openstreetmap.org/api/0.6/';
OsmService = function($http) {
this.ngHttp = $http;
/** Converter from XML to json. */
this.x2js = new X2JS({
// All XML nodes under <osm> can be repeated.
arrayAccessFormPaths: [/osm\..*/]
});
};
/**
* Converts an array of tags from array to map.
*/
tagMap = function(tags) {
var result = {};
(tags || []).forEach(tag => {
result[tag._k] = tag._v;
});
return result;
};
/** Returns a leaflet LatLng object for the given node. */
latLngFromNode = function(node) {
return node && node._lat && node._lon && L.latLng([node._lat, node._lon]);
};
/**
* Returns bounds for the given list of nodes.
*/
getBounds = function(nodes) {
var bounds = L.latLngBounds();
nodes.forEach(node => {
bounds.extend(latLngFromNode(node));
});
return bounds;
};
/**
* Converts the given list of nodes to a list of segments (from node, to node).
*/
getSegments = function(nodes) {
var segments = [];
for (var i = 1; i < nodes.length; i++) {
segments.push({from: nodes[i - 1], to: nodes[i]});
}
return segments;
};
/**
* Calls the given URL and returns OSM data as a list of json objects.
* Adds a tagMap field to objects which stores a key-value map of the
* object's tags.
*/
OsmService.prototype.fetchOsm = function(path, objectType) {
return this.ngHttp.get(API_URL_BASE + path).then(response => {
var data = this.x2js.xml_str2json(response.data).osm[objectType] || [];
data.forEach(item => {
if (item.tag) {
item.tagMap = tagMap(item.tag);
}
});
return data;
});
};