0

I'm having some trouble returning the latLng value for the following function.

function getUserPosition() {
    var latLng;

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
            function (position) {
                latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); // #1
            }, function () {
                latLng = defaultPosition(); // #2
            }
        );
    } else {
        latLng = defaultPosition(); // #3
    }

    return latLng;
}

Assume that defaultPosition() returns a valid set of coordinates.

I've marked three latLng assignments that are part of my latest 'catch-all' approach but still no luck.

I've checked out other related answers but still can't seem to get my head around my particular issue, so sorry for the repost.

Thanks in advance.

1 Answers1

1

You can't do that because of the asynchronous nature of the location API, instead you need to use a callback based approach where the callback function will be invoked once the locaion API returns the value.

function getUserPosition(callback) {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(

        function (position) {
            callback(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
        }, function () {
            callback(defaultPosition()); // #2
        });
    } else {
        callback(defaultPosition()); // #3
    }
}

getUserPosition(function(latLng){
    //do all operations that depends on latLng here in the callback function
})
Arun P Johny
  • 365,836
  • 60
  • 503
  • 504