0

My Code:

var latlng = {lat: 7, lng: 7};

function findLatLng() {
    var testLocation = '350 Victoria St, Toronto';

    axios.get('https://maps.googleapis.com/maps/api/geocode/json', {
        params: {
            address: testLocation,
            key: 'MY KEY',
        }
    })
    .then(function(response) {
        console.log(response.data.results[0].geometry.location);
        return response.data.results[0].geometry.location;
    })
    .catch(function(error) {
        console.log(error);
    });
}

latlng = findLatLng();
console.log(latlng);

In the console, latlng is logged as undefined, but the console.log(response.data.results[0].geometry.location) is logged with the proper value;
it is also logged afterwards even though it should have executed first.

I think this is because the code continues despite findLatLng() not being done with the request but I'm not sure. When I check the value of latlng in the console afterwards, it becomes the proper value.

What is the issue and how do I fix this please?

NickS1
  • 496
  • 1
  • 6
  • 19
  • `latlng = findLatLng();` doesn’t make sense. `findLatLng` doesn’t return anything. – Sebastian Simon Sep 30 '21 at 23:44
  • See also here: https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron –  Sep 30 '21 at 23:46
  • return response.data.results[0].geometry.location; also doesn't make sense here. try to update latlng in success/error cases – Volodymyr Sen Sep 30 '21 at 23:46

0 Answers0