简体   繁体   中英

How to retrieve local variable (geolocation HTML5 and Google Maps API)?

I am stuck with this problem : I would like to retrieve the position defined by geolocation in order to use it in my calcRoute function as the start point for example, here is the code :

function calcRoute(){
   var pos;

    navigator.geolocation.getCurrentPosition
    (
        function(position) 
        {
            pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
        }
    );

    var start = pos;
    alert(start); // pb here : start is undefined, how could I get the pos value ?
    //...
}

Thanks a lot for your help!

The function you define is a callback function that is called once the location is retrieved.

It will fail for two reasons:

  • you don't know if the callback function will be called at all, not to say before the rest of calcRoute (which is actually extremely unlikely as it is asynchronous)
  • even if it was called before the end of calcRoute , the pos is in a different scope so you cannot change it this way.

You may be tempted to resort to global variables to fix the second issue but you won't be able to fix the first one. Why not put the rest of your code in the callback function?

function calcRoute(){
  navigator.geolocation.getCurrentPosition
  (
      function(position) 
      {
          var pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
          var start = pos;
          alert(start);
      }
  );

}

EDIT: more detailed answer to explain why go this route

function calcRoute(){
var pos;

navigator.geolocation.getCurrentPosition
(
    function(position) 
    {
        pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
        var start = pos;
        alert(start);
    }
);


//...
}

As it is a callback it will be executed later. but you can devide your code and let it execute.

function calcRoute(){

    navigator.geolocation.getCurrentPosition
    (
        function(position) 
        {
           var pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
           furtherCode(pos);
        }
    );

    }

function furtherCode(position){
    var start = pos;
    alert(start); 
    //...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM