简体   繁体   中英

How to assign global variable inside of an asynchronous function in Javascript?

Console logging the lat returns undefined , while I want to assign the value of position.coords.latitude to it. What is the problem?

 $(document).ready(function(){ var lat, lon; if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { lat=position.coords.latitude; lon=position.coords.longitude; }); console.log(lat); } }); 

You can't log there, you must need callback function to achieve your goal

<script>
  var x = document.getElementById("demo");
  function getLocation() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(showPosition);
    } else {
      x.innerHTML = "Geolocation is not supported by this browser.";
   }
 }
function showPosition(position) {
  console.log("Latitude: " + position.coords.latitude +" Longitude: "          + position.coords.longitude)
  x.innerHTML = "Latitude: " + position.coords.latitude + 
  "<br>Longitude: " + position.coords.longitude; 
}
</script>

use callback function $(document).ready(function(){ var lat, lon;

  if (navigator.geolocation) {
     navigator.geolocation.getCurrentPosition(function(position) {
        lat=position.coords.latitude;
        lon=position.coords.longitude;
        callbackFunction();
     });
   }

   function callbackFuncton(){
      console.log(lat);
      //you can use your lat and lon here
   }
});    

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