React native setting/accessing a variable inside a

2019-08-17 19:49发布

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

}

1条回答
仙女界的扛把子
2楼-- · 2019-08-17 20:27

Geocoder.getFromLocation() takes time to occur.

You need to wait until it finishes

查看更多
登录 后发表回答