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!
The
navigator.geolocation.getCurrentPositionmethod is asynchronous. Your functions have returnedundefinedbefore 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: