简体   繁体   English

反应本机设置/访问函数中的变量

[英]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. 我正在尝试将变量lat和lng设置为地址解析器返回的坐标。 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. 我认为lat和lng可以从Geocoder代码内部访问,该代码表示​​Geocoder.getFromLocation(inputWhere).then(...),但是在此之外,似乎并没有将变量设置为Geocoder的坐标。 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. 我已经测试过Geocoder可以正常工作,并且满足“如果”条件。 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. Geocoder.getFromLocation()需要花费一些时间。

You need to wait until it finishes 您需要等待直到完成

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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