diff --git a/weather-app/app.js b/weather-app/app.js index 2056d04..b1a812f 100644 --- a/weather-app/app.js +++ b/weather-app/app.js @@ -1,7 +1,5 @@ -// Mapbox token: -// pk.eyJ1IjoiamF5d2xsIiwiYSI6ImYyZjkyMGNlOTgyNGQ5ZWM5ZDExN2FjNGYwMDZmNTQ4In0.y3lv5ddmGhVNSL7wfMpB0g - const request = require('request') +const geocode = require('./utils/geocode') const url = 'https://api.darksky.net/forecast/0466bccb953c0b9daeb091a529da2c0d/37.8267,-122.4233?units=si' @@ -15,16 +13,23 @@ const url = 'https://api.darksky.net/forecast/0466bccb953c0b9daeb091a529da2c0d/3 // } // }) -const geocodeURL = 'https://api.mapbox.com/geocoding/v5/mapbox.places/philadelphia.json?access_token=pk.eyJ1IjoiamF5d2xsIiwiYSI6ImYyZjkyMGNlOTgyNGQ5ZWM5ZDExN2FjNGYwMDZmNTQ4In0.y3lv5ddmGhVNSL7wfMpB0g&limit=1' +// const geocodeURL = 'https://api.mapbox.com/geocoding/v5/mapbox.places/philadelphia.json?access_token=pk.eyJ1IjoiamF5d2xsIiwiYSI6ImYyZjkyMGNlOTgyNGQ5ZWM5ZDExN2FjNGYwMDZmNTQ4In0.y3lv5ddmGhVNSL7wfMpB0g&limit=1' -request({ url: geocodeURL, json: true }, (error, response) => { - if (error) { - console.log('Unable to connect to location services!') - } else if (response.body.features.length === 0) { - console.log ('Unable to find location. Try another search.') - } else { - const latitude = response.body.features[0].center[1] - const longitude = response.body.features[0].center[0] - console.log(latitude, longitude) - } +// request({ url: geocodeURL, json: true }, (error, response) => { +// if (error) { +// console.log('Unable to connect to location services!') +// } else if (response.body.features.length === 0) { +// console.log ('Unable to find location. Try another search.') +// } else { +// const latitude = response.body.features[0].center[1] +// const longitude = response.body.features[0].center[0] +// console.log(latitude, longitude) +// } +// }) + + + +geocode('Boston', (error, data) => { + console.log('Error', error) + console.log('Data', data) }) diff --git a/weather-app/utils/geocode.js b/weather-app/utils/geocode.js new file mode 100644 index 0000000..0a92543 --- /dev/null +++ b/weather-app/utils/geocode.js @@ -0,0 +1,21 @@ +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' + + request({ url: url, json: true }, (error, response) => { + if (error) { + callback('Unable to connect to location services!', undefined) + } else if (response.body.features.length === 0) { + callback('Unable to find location. Try another search.', undefined) + } else { + callback(undefined, { + latitude: response.body.features[0].center[1], + longitude: response.body.features[0].center[0], + location: response.body.features[0].place_name + }) + } + }) +} + +module.exports = geocode