views:

68

answers:

1

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?

+3  A: 

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 getCurrentPosition function, 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 meLatLng with customCallBack(meLatLng) and then defined customCallBack somewhere along the line.

Or, since you have already defined where in the global scope you could try and replace return meLatLng with where = meLatLng and then remove where = from where = navigatior.geoloc....

If what I suspect is right, the last method wont work, since I believe getCurrentPosition is 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.

Kristoffer S Hansen
yeah it seems it runs out of mainflow, so I'll have to look into this CallBack idea .. thanks :)
keranm