I have been trying to create some seed files, while also using the google api, to create some longitude and latitudes for each city. The whole process and code works, but I believe there is an issue with the asynchronous call as I cannot properly save the coordinates. Here is a snippet from my code:
var coordinates = getCoordinates("syndey", "australia");
console.log("these are the coordinates " + coordinates);
function getCoordinates(city, country) {
var coordinates = {
lat: Number,
lng: Number
};
const url = "https://maps.googleapis.com/maps/api/geocode/json?components=locality:"+city+"|country:"+country +"&key=MYAPIKEY";
request(url, (err, resp, body)=> {
body = JSON.parse(body);
console.log("this is the body: " + JSON.stringify(body.results[0].geometry.location.lat));
if (err) {
res.status(401).json({message: "error"});
} else {
coordinates.lat = body.results[0].geometry.location.lat;
coordinates.lng = body.results[0].geometry.location.lng;
}
console.log("before exit: " + JSON.stringify(coordinates));
return coordinates;
});
}
When the code executes, i get the following consoles in my terminal:
these are the coordinates undefined
this is the body: -33.8688197
before exit: {"lat":-33.8688197,"lng":151.2092955}
As you can see, the coordinates are Undefined, and its clearly because the before exit console log is executed after.
I did try a callback but it did not work.
Any ideas?
Thanks Andreas