In this section, we'll be refactoring app.js, taking a lot of the complex logic related to geocoding and moving it into a separate file. Currently, all of the logic for making the request and determining whether or not the request succeeded, our if else statements, live inside of app.js:
request({
url: `https://maps.googleapis.com/maps/api/geocode/json?address=${encodedAddress}`,
json: true
}, (error, response, body) => {
if (error) {
console.log('Unable to connect Google servers.');
} else if (body.status === 'ZERO_RESULTS') {
console.log('Unable to find that address.');
} else if (body.status === 'OK') {
console.log(`Address: ${body.results[0].formatted_address}`);
console.log(`Latitude: ${body.results[0].geometry.location.lat}`);
console.log(`Longitude: ${body.results[0].geometry.location.lng}`);
}
});
This is not exactly reusable and it really doesn't belong here. What I'd like to do before we add even more logic related to fetching the forecast, that's the topic of the next section, is break this out into its own function. This function will live in a separate file, like we did for the notes application.
In the notes app we had a separate file that had functions for adding, listing, and removing notes from our local adjacent file. We'll be creating a separate function responsible for geocoding a given address. Although the logic will stay the same, there really is no way around it, it will be abstracted out of the app.js file and into its own location.