0

im struggling to understand why i cant access the properties that are created and returned in my function. if i console log the object itself. its successful, however, if i console log object.prop i get undefined. Here is my code

 function geocodeAddress(value) {
            let geocoder = new google.maps.Geocoder(); // eslint-disable-line
            let data = {};
            geocoder.geocode({'address': value}, function(results, status) {
                if (status === 'OK') {
                    data.longitude = results[0].geometry.location.lng();
                    data.latitude = results[0].geometry.location.lat();
                }
            });
            return data;
        }

        const place = geocodeAddress('Leeds');

        console.log(place.longitude,place.latitude);
Umar Gora
  • 69
  • 8

1 Answers1

0

Property of data is set in geocoder.geocode function which is async function that's why It will always return {} You have several ways to handle aysnc work one of them is using Promise

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

function geocodeAddress(value) {
    return new Promise(function(resolve, reject) {
        let geocoder = new google.maps.Geocoder(); // eslint-disable-line
        let data = {};
        geocoder.geocode({
            'address': value
        }, function(results, status) {
            if (status === 'OK') {
                data.longitude = results[0].geometry.location.lng();
                data.latitude = results[0].geometry.location.lat();
                resolve(data)
            } else {
                reject(status);
            }
        });

    })
}

let place = {};
geocodeAddress('Leeds').then(function(response) {
    place = response
    console.log(place.longitude, place.latitude);
}, function(error) {
    console.log(error);
})

=> another option is using async/await

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

Nishant Dixit
  • 5,388
  • 5
  • 17
  • 29