I’m trying to do something that should be pretty simple – but it’s doing my head in.
I can’t seem to get a variable to return from a function
var where;
if (navigator.geolocation) {
where = navigator.geolocation.getCurrentPosition(function (position) {
// okay we have a placement - BUT only show it if the accuracy is lower than 500 mtrs
//if (position.coords.accuracy <= 500 ) {
// put their lat lng into google
var meLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var image = "images/map_blue.png";
var myMarker = new google.maps.Marker({
position: meLatLng,
map: map,
title: "Your location, as provided by your browser",
icon: image,
zIndex: 50
});
//} // end 500 mtrs test
return meLatLng;
});
alert("A: "+where);
}
I have a global variable called where, I’m trying to fill it with LatLng information received from the browser using navigator.geolocation – it plots the user on the map – but alert(where) always returns undefined
What am I doing wrong?
Short answer, nothing,
Bit longer answer, well… you see, the problem is that it would appear that your anonymous function returns its value to the
getCurrentPositionfunction, which it seems doesnt return anything at all.In order to use your returned value you should instead use a callBack or handle the data where it is…
Simply try replacing
return meLatLngwithcustomCallBack(meLatLng)and then definedcustomCallBacksomewhere along the line.Or, since you have already defined
wherein the global scope you could try and replacereturn meLatLngwithwhere = meLatLngand then removewhere =fromwhere = navigatior.geoloc....If what I suspect is right, the last method wont work, since I believe
getCurrentPositionis asynchronous, meaning that you leave the standard flow of the application as soon as you call it. Which is why you supply a function to it in the first place.