-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathgetGeocode.js
71 lines (63 loc) · 2.22 KB
/
getGeocode.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
const dotenv = require("dotenv");
//note: this only works locally; in Lambda we use environment variables set manually
dotenv.config();
const { Client } = require("@googlemaps/google-maps-services-js");
const { generateKey } = require("./data/dataDefaulter");
const axios = require("axios");
const axiosRetry = require("axios-retry");
axiosRetry(axios, { retries: 5, retryDelay: axiosRetry.exponentialDelay });
const getGeocode = async (name, street, zip) => {
const address = `${name},MA,${street},${zip}`;
const client = new Client();
try {
const resp = await client.geocode(
{
params: {
address,
key: process.env.GOOGLE_API_KEY,
},
},
axios
);
return resp.data;
} catch (e) {
console.error(e.response.data);
}
};
const getAllCoordinates = async (locations, cachedResults = {}) => {
const existingLocations = cachedResults.reduce((acc, location) => {
const { latitude, longitude } = location;
if (latitude && longitude) {
acc[generateKey(location)] = {
latitude,
longitude,
};
return acc;
} else {
return acc;
}
}, {});
const coordinateData = await Promise.all(
locations.map(async (location) => {
const { name = "", street = "", zip = "" } = location;
const locationInd = generateKey(location);
if (existingLocations[locationInd]) {
return { ...location, ...existingLocations[locationInd] };
} else {
const locationData = await getGeocode(name, street, zip);
if (locationData) {
return {
...location,
latitude:
locationData?.results[0].geometry.location.lat,
longitude:
locationData?.results[0].geometry.location.lng,
};
} else return location;
}
})
);
return coordinateData;
};
exports.getAllCoordinates = getAllCoordinates;
exports.getGeocode = getGeocode;