-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
91 lines (70 loc) · 1.8 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
87
88
89
90
const fs = require("fs");
const googleMapsClient = require("@google/maps").createClient({
key: process.env["GOOGLE_TOKEN"]
});
const responses = [];
const db = require("./db.json");
const cache = {};
let count = 0;
let i = 0;
db.forEach((list) => {
list.forEach((municipality) => {
if(municipality.lat){
cache[municipality.country + municipality.municipality] = municipality;
i++;
}
});
});
console.log(i);
fs.readdirSync("./sources").map(file => {
return {
code: file.split(".")[0],
data: require("./sources/"+file).municipalities
};
}).filter((value, key) => {
return key > -1;
//return key < 1;
}).map(list => {
return new Promise(resolve => {
const promises = list.data.map(municipality => {
return new Promise((resolve) => {
if(cache[list.code + municipality]){
console.log("cache hit");
count++;
resolve(cache[list.code + municipality]);
return;
}
googleMapsClient.geocode({
address: municipality + ", " + list.code
}, function(err, response) {
if (!err) {
const result = {
country: list.code,
municipality: municipality,
lat: (response.json.results[0] || {geometry: {location: {lat: undefined}}}).geometry.location.lat,
lng: (response.json.results[0] || {geometry: {location: {lng: undefined}}}).geometry.location.lng
};
console.log(count);
count++;
resolve(result);
} else {
console.log(err);
const result = {
country: list.code,
municipality: municipality,
};
console.log(count);
resolve(result);
}
});
});
});
resolve(Promise.all(promises));
});
}).map((list) => {
responses.push(list);
});
Promise.all(responses).then((list) => {
fs.writeFileSync("./db.json", JSON.stringify(list));
console.log(count);
});