I'm wrote a function (with the help of this tutorial https://www.youtube.com/watch?v=pRiQeo17u6c) to geocode addresses using google maps. I want the function to return coordinates of any given address. Eventually, I'm hoping to write a script that loops over an array of addresses and returns a array of their coordinates in the form of [lat, lng]
.
However, before we go to fast, this question is simply about returning one value. Please see the script below.
The function works. If I for example call geocode('New York')
and enable console.log(latlng)
within the function, it properly logs [40.7127753,-74.0059728]
. However, if I call the function to appoint a variable like var coord_address_1 = geocode("New York")
this variable is undefined. What am I doing wrong? I have read these posts How do I return the response from an asynchronous call? and concluded that it has probably to do with the fact that I want latlng
returned before it is assigned. However, as I am new to JS I didn't really understand how to avoid this. I tried around with .then(function(latlng) {return latlng;})
and callback(latlng);
but no luck there either (ReferenceError: callback is not defined
).
<script>
function geocode(address) {
axios
.get("https://maps.googleapis.com/maps/api/geocode/json", {
params: {
address: address,
key: "API_KEY"
}
})
.then(function(response) {
// create variable in desired format
var latlng =
"[" +
[
response.data.results[0].geometry.location.lat,
response.data.results[0].geometry.location.lng
] +
"]";
// this works
// console.log(latlng);
return latlng;
})
.catch(function(error) {
console.log(error);
});
}
var coord_address_1 = geocode("New York");
console.log(coord_address_1); // undefined
</script>