-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
52 lines (42 loc) · 1.36 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
const fetch = require('node-fetch');
const pThrottle = require('p-throttle');
const { GOOGLE_MAPS_API_KEY } = process.env;
const url = (address, key = GOOGLE_MAPS_API_KEY) =>
`https://maps.googleapis.com/maps/api/geocode/json?address=${address}&key=${key}`;
const findLatLng = (apiKey, opts = { debug: false }) => async addresses => {
const uniqueAddresses = new Set();
// eslint-disable-next-line no-restricted-syntax
for (const address of addresses) {
if (!uniqueAddresses.has(address)) {
uniqueAddresses.add(address);
}
}
const throttledFetch = pThrottle(
async x =>
new Promise(async resolve => {
const { results, status } = await fetch(
url(encodeURIComponent(x), apiKey),
).then(res => res.json());
if (status !== 'OK' || (!results || results.length === 0)) {
if (opts.debug) {
console.warn(`Could not find lat/lng for ${x}`); // eslint-disable-line no-console
}
return resolve({
address: x,
lat: null,
lng: null,
});
}
const { geometry: { location: { lat, lng } } } = results[0];
return resolve({
address: x,
lat,
lng,
});
}),
40,
1000,
);
return Promise.all(Array.from(uniqueAddresses).map(throttledFetch));
};
module.exports = findLatLng;