-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
nominatim.js
115 lines (94 loc) · 3.27 KB
/
nominatim.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
107
108
109
110
111
112
113
114
115
import { json as d3_json } from 'd3-fetch';
import RBush from 'rbush';
import { geoExtent } from '../geo';
import { utilQsString } from '../util';
import { localizer } from '../core';
import { nominatimApiUrl } from '../../config/id.js';
var apibase = nominatimApiUrl;
var _inflight = {};
var _nominatimCache;
export default {
init: function() {
_inflight = {};
_nominatimCache = new RBush();
},
reset: function() {
Object.values(_inflight).forEach(function(controller) { controller.abort(); });
_inflight = {};
_nominatimCache = new RBush();
},
countryCode: function (location, callback) {
this.reverse(location, function(err, result) {
if (err) {
return callback(err);
} else if (result.address) {
return callback(null, result.address.country_code);
} else {
return callback('Unable to geocode', null);
}
});
},
reverse: function (loc, callback) {
var cached = _nominatimCache.search(
{ minX: loc[0], minY: loc[1], maxX: loc[0], maxY: loc[1] }
);
if (cached.length > 0) {
if (callback) callback(null, cached[0].data);
return;
}
var params = { zoom: 13, format: 'json', addressdetails: 1, lat: loc[1], lon: loc[0] };
var url = apibase + 'reverse?' + utilQsString(params);
if (_inflight[url]) return;
var controller = new AbortController();
_inflight[url] = controller;
d3_json(url, {
signal: controller.signal,
headers: {
'Accept-Language': localizer.localeCodes().join(',')
}
})
.then(function(result) {
delete _inflight[url];
if (result && result.error) {
throw new Error(result.error);
}
var extent = geoExtent(loc).padByMeters(200);
_nominatimCache.insert(Object.assign(extent.bbox(), {data: result}));
if (callback) callback(null, result);
})
.catch(function(err) {
delete _inflight[url];
if (err.name === 'AbortError') return;
if (callback) callback(err.message);
});
},
search: function (val, callback) {
const params = {
q: val,
limit:10,
format: 'json'
};
var url = apibase + 'search?' + utilQsString(params);
if (_inflight[url]) return;
var controller = new AbortController();
_inflight[url] = controller;
d3_json(url, {
signal: controller.signal,
headers: {
'Accept-Language': localizer.localeCodes().join(',')
}
})
.then(function(result) {
delete _inflight[url];
if (result && result.error) {
throw new Error(result.error);
}
if (callback) callback(null, result);
})
.catch(function(err) {
delete _inflight[url];
if (err.name === 'AbortError') return;
if (callback) callback(err.message);
});
}
};