2

Folks!

I'm trying to get the latitude or longitude of a location using the Google Maps API. But I don't know how to return a value using the Fetch API and its promises.

I can log the latitude and longitude with:

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

But I want to encapsulate this code in a function:

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

Could someone point me what is wrong? Thanks you all!

Edit: Here you can find a JS Bin with the code

vcamargo
  • 21
  • 2
  • 3

1 Answers1

4

You must use .then to handle the result of a promise:

function getLatitudeOrLongitude(url, LatitudeOrLongitude) {
  return 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
    })
}

getLatitudeOrLongitude(url, 'latitude')
  .then((latitudeOfLondon) => console.log(latitudeOfLondon));
SimpleJ
  • 13,812
  • 13
  • 53
  • 93