-1

I have JS code which is doing geolocation, so I converted address to coordinates, but I can not get values from callback function:

    $(function () {
    var longitude;
    var latitude;

    GMaps.geocode({
        address: geolocate_address,
        callback: function(results, status) {
            if (status == 'OK') {
                var latlng = results[0].geometry.location;
                latitude = latlng.lat();
                longitude = latlng.lng();
            }
        }
    });

    console.log(latitude);
    console.log(longitude);
    });

Shows empty variables.

When I do alert in callback function it shows coordinates.

How to get coordinates outside that function?

1 Answers1

0

Your callback is async, at the moment you invoke console.log(latitude);, latitude still does not have value set, as client is still waiting for server response.

Try to handle data after you receive it:

GMaps.geocode({
        address: geolocate_address,
        callback: function(results, status) {
            if (status == 'OK') {
                var latlng = results[0].geometry.location;
                latitude = latlng.lat();
                longitude = latlng.lng();
                handleCallback(latitude, longitude);
            }
        }
    });

function handleCallback(latitude, longitude){
    console.log(latitude);
    console.log(longitude);
}
Ivan Jovović
  • 5,238
  • 3
  • 29
  • 57