0

I'm trying to make it so I can write a function which defines a variable, and then call that function within another function to give me the variable.

Here's what I've done:

function getLat(){
  navigator.geolocation.getCurrentPosition(function(lat){
    var latCoord = lat.coords.latitude;
    return latCoord;
  });
}
function getLong(){
  navigator.geolocation.getCurrentPosition(function(lon){
    var longCoord = lon.coords.latitude;
    return longCoord;
  });
}
function getImage(){
  var the_lat = getLat(),
      the_lon = getLong();
  console.log(the_lat + ' ' + the_lon);
}
getImage();

As you can see I have the functions getLat(), and getLong() to grab the latitude, as well as the longitude of the person. Then, in getImage() I want to be able to call getLat() in a variable to assign latCoord to that variable. I was hoping return latCoord; would do this, but I was mistaken.

Is this possible, or should I be going about it a different way? If so, may I see an example of how I should be doing this?

Here's a jsbin http://jsbin.com/ulelix/edit

Let me know if I need to clarify anything, or if you need me to add any information and I will do so as appropriate. I've searched around, but can't seem to get the answer I'm looking for. Any help is appreciated, Thanks!

j08691
  • 204,283
  • 31
  • 260
  • 272
MoDFoX
  • 2,134
  • 2
  • 21
  • 22

1 Answers1

1

The navigator.geolocation.getCurrentPosition method is asynchronous. Your functions have returned undefined before the callbacks are executed.

You need to move any code that relies on the response from that method into the callback.

I would suggest combining your two functions into one, since both latitude and longitude are available in the callback:

function getLatLng(){
    navigator.geolocation.getCurrentPosition(function(pos) {
        var lat = pos.coords.latitude,
            lng = post.coords.longitude;

        //Do stuff relying on lat/lng here...
    });
}
James Allardice
  • 164,175
  • 21
  • 332
  • 312
  • Alright, that's what I thought I would have to do. I had originally done it this way, but was trying to change it around to clean up some messy code. I'll just rewrite it this way and hopefully clean it up while doing so. Thank you. – MoDFoX Jun 14 '12 at 20:05