-
Notifications
You must be signed in to change notification settings - Fork 1
/
common.js
61 lines (47 loc) · 1.34 KB
/
common.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
/*
* The common.js module includes common functions that other server related modules may use.
*/
const fetch = require("node-fetch");
const common = {};
common.convertAddressToCoords = async (address) => {
// Sleep for 2 seconds before continuing to prevent massive requests to OSM.
await new Promise(r => setTimeout(r, 2000));
// No address specified.
if(!address) {
return null;
}
// Convert whitespace to %20 for and remove #[num]
address = await address.replace(/\s+/g, "%20");
// address = await address.replace(/#.*\s/, "%20");
let res;
try {
res = await fetch("https://nominatim.openstreetmap.org/search?q=" + address + "&format=json");
} catch(err) {
console.log(err);
return null;
}
if(!res.ok) {
console.log(res.statusText);
return null;
}
let data;
try { // Try to parse JSON response.
data = await res.json();
} catch(err) {
console.log(err);
return null;
}
const location = data[0]; // Get first search result.
// Location exists!
if(location) {
return {
lat: location.lat,
lon: location.lon
}
// Location doesn't exist :(
} else {
console.log(address + " not found on OSM!");
return null;
}
};
module.exports = common;