Hello everyone!
I'm currently working on a project that requires me to retrieve the latitude or longitude of a location using the Google Maps API. However, I am facing an issue with returning values using the Fetch API and its promises.
I have successfully logged the latitude and longitude using the following code:
let url = 'https://maps.googleapis.com/maps/api/geocode/json?address=london'
fetch(url)
.then(response => response.json())
.then(data => {
console.log(data.results[0].geometry.location.lat)
console.log(data.results[0].geometry.location.lng)
})
Output:
51.5073509
0.1277583
However, my goal is to create a function to encapsulate this code:
function getLatitudeOrLongitude(url, LatitudeOrLongitude) {
fetch(url)
.then(response => response.json())
.then(data => {
if (LatitudeOrLongitude === 'latitude')
return data.results[0].geometry.location.lat
else
return data.results[0].geometry.location.lng
})
}
let latitudeOfLondon = getLatitudeOrLongitude(url, 'latitude')
console.log(latitudeOfLondon)
Output:
undefined
I would greatly appreciate it if someone could help point out what I am doing wrong. Thank you all in advance!
Edit: Click here to access a JS Bin containing the code snippet.