forked from abarlow85/latlng-to-zip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
44 lines (35 loc) · 1.26 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
const axios = require('axios');
const GEOCODE_ROOT_URL = 'https://maps.googleapis.com/maps/api/geocode/json?latlng='
const buildGeocodeUrl = ({longitude, latitude}) => {
// latitude goes first in query
return `${GEOCODE_ROOT_URL}${latitude},${longitude}&key=AIzaSyBErLdf4XxPa74wrrdyJUyPvnlRxRa0fT4`;
};
const reverseGeocode = (region) => {
return new Promise((resolve, reject) => {
const url = buildGeocodeUrl(region);
axios.get(url)
.then(({ data }) => {
if (data.error_message) {
return Promise.reject({ response: { data: data.error_message } });
}
const { results } = data;
if (results.length === 0) {
return Promise.reject({ response: { data: 'No results' } });
}
// results[0] is the result in closest
// proximity to the provided longitude and latitude
const { address_components } = results[0];
const postal_code = address_components
.find(component => component.types[0] === 'postal_code');
if (!postal_code) {
return Promise.reject({ response: { data: 'No results' } });
}
const zip = postal_code.long_name || postal_code.short_name;
resolve(zip);
})
.catch(err => {
reject(err);
});
});
};
module.exports = reverseGeocode;