0

I can't figure out why I'm getting this result, I've never been able to master JavaScript because I'm always intimidated by how erratic the code behaves compared to Python or Java.

I need the variable lng_ to be set to the current Longitude, once I figure that out I will do the same with lat_. Here's my code:

var lng_ = navigator.geolocation.getCurrentPosition(GetLong);
var lat_ = navigator.geolocation.getCurrentPosition(GetLat);    

function GetLong(location) 
{
    console.log(location.coords.longitude);
    var ret = location.coords.longitude;
    return ret;
}

console.log(lng_);

function GetLat(location) 
{
    return(location.coords.latitude);
}

if you look at the function GetLong(location) it should return the value of longitude AND include a JavaScript log to show if it's working.

And according to my JavaScript log, I get the correct result

-122.15616500000002

But when I store this value in ret and return it, the final console.log() comes up with undefined

How does JavaScript even know what kind of object it's returning whether it's a string or int? And what is the solution to my problem?

Alex R.
  • 4,664
  • 4
  • 30
  • 40
user1504605
  • 579
  • 5
  • 19
  • 4
    `navigator.geolocation.getCurrentPosition()` doesn't return anything. It passes the "return value" to the callback. – Blender Mar 26 '14 at 03:30
  • possible duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – Bergi Mar 26 '14 at 03:34

1 Answers1

2

You only have to call getCurrentPosition() once with a callback function, it doesn't actually return the position when called; the reason for this is that the position will not be immediately available:

function getPosition(location)
{
    var lng_, lat_;

    lng_ = location.coords.longitude;
    lat_ = location.coords.latitude;

    // do stuff with position here
}

navigator.geolocation.getCurrentPosition(GetPosition);

It works much like how other asynchronous operations work in JavaScript.

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309