1
0
CompleteNodeJS/weather-app/utils/geocode.js

22 lines
789 B
JavaScript
Raw Normal View History

2019-08-25 20:57:02 +00:00
const request = require('request')
const geocode = (address, callback) => {
const url = 'https://api.mapbox.com/geocoding/v5/mapbox.places/' + encodeURIComponent(address) + '.json?access_token=pk.eyJ1IjoiamF5d2xsIiwiYSI6ImYyZjkyMGNlOTgyNGQ5ZWM5ZDExN2FjNGYwMDZmNTQ4In0.y3lv5ddmGhVNSL7wfMpB0g&limit=1'
2019-09-29 18:36:49 +00:00
request({ url, json: true }, (error, {body}) => {
2019-08-25 20:57:02 +00:00
if (error) {
callback('Unable to connect to location services!', undefined)
2019-09-29 18:36:49 +00:00
} else if (body.features.length === 0) {
2019-08-25 20:57:02 +00:00
callback('Unable to find location. Try another search.', undefined)
} else {
callback(undefined, {
2019-09-29 18:36:49 +00:00
latitude: body.features[0].center[1],
longitude: body.features[0].center[0],
location: body.features[0].place_name
2019-08-25 20:57:02 +00:00
})
}
})
}
module.exports = geocode