2

I have this function that is trying to return the latitude and longitude as a string when called. However when i call it with an alert it returns undefined. But when I alert the data.coords.latitude/longitude it gives me the correct values. Any help is greatly appreciated.

function GetLocation() {
    var jsonLocation;
    navigator.geolocation.getCurrentPosition(function (data) {
        jsonLocation = data.coords.latitude+','+data.coords.longitude;
    });
    return String(jsonLocation);
}
alert(GetLocation());
Dan Dascalescu
  • 143,271
  • 52
  • 317
  • 404
David W
  • 1,833
  • 5
  • 21
  • 25

2 Answers2

4

getCurrentPosition() expects a callback:

function getLocation(callback) {
    navigator.geolocation.getCurrentPosition(function (data) {
        var jsonLocation = data.coords.latitude+','+data.coords.longitude;
        callback(jsonLocation);
    });
}

getLocation(alert);
Dan Dascalescu
  • 143,271
  • 52
  • 317
  • 404
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • callback() is not defined..Why? – Mostafa Aug 11 '16 at 11:42
  • @Mostafa: Because you didn't pass one to your `getLocation` call? – Bergi Aug 11 '16 at 11:43
  • Can we use custom call function instead of just `alert()` ?I return an object of coordinates data.how can handle this? – Mostafa Aug 11 '16 at 12:01
  • Sure, you are even *supposed* to use a custom function there, that's the whole point of callbacks. But no, you [cannot `return` from there](http://stackoverflow.com/q/14220321/1048572) – Bergi Aug 11 '16 at 12:04
  • Thanks..verrry usefull. – Mostafa Aug 11 '16 at 12:36
  • I have a fiddle of my code here ,,but still not work .( https://jsfiddle.net/6038tcrw/ ) – Mostafa Aug 11 '16 at 12:37
  • @Mostafa: The `return_result` can't work, you might want to read the thread I linked again. Place the final log inside the `CallBack`. Otherwise should be fine, if there's something left please [ask a new question](http://stackoverflow.com/questions/ask) about it. – Bergi Aug 11 '16 at 12:42
  • Thanks a lot.you save my hour. – Mostafa Aug 11 '16 at 13:08
  • I have a console.log in my callback function but it isent being written. i got the popup permissions dialoge and i clicked accept though. – CDM social medias in bio Apr 11 '20 at 20:31
0

I changed up the code so the callback would alert the information when the getCurrentPosition returns

function RequestLocation() {
            navigator.geolocation.getCurrentPosition(function (data) {
                SendLocation(String(data.coords.latitude + ',' + data.coords.longitude));
            });
        }
        function SendLocation(cords)
        {
            alert(cords);
        }

        RequestLocation();
David W
  • 1,833
  • 5
  • 21
  • 25