简体   繁体   中英

React native setting/accessing a variable inside a function

I'm trying to set the variables lat and lng to the coordinates returned by the geocoder. I think that lat and lng are accessible from inside the geocoder code where it says Geocoder.getFromLocation(inputWhere).then(...), but then outside of that, it doesn't seem to have set the variables to the geocoder's coordinates. Am I missing something about the variable scope? I've commented what the alerts are returning. I've tested that the geocoder works fine and that the "if" condition is being satisfied. Any help appreciated, thanks!

submitData = (inputWhere) => {

var lat = 0;
var lng = 0;

if(inputWhere != '') {
  Geocoder.getFromLocation(inputWhere).then(
   json => { 
    var location = json.results[0].geometry.location;
    alert(lat); // Here it says 0
    lat = location.lat; // 40
    lng = location.lng;
    alert(lat); // Here it says 40
   },
   error => {
    alert(error);
   }
 );
 alert(lat); // Here it says 0
}
alert(lat); // Here it says 0

}

Geocoder.getFromLocation() takes time to occur.

You need to wait until it finishes

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