在javascript中更新全局变量

Update global variable in javascript

本文关键字:全局变量 更新 javascript      更新时间:2023-09-26

我在javascript中有一个全局变量,比如

var EventLocation = {
        'center' : '35.59214,-121.046048',
        'zoom' : 10
};

现在,在一个函数中,我们将这个变量更新为

var geocoder = new google.maps.Geocoder();
    var address =  $j('#EventLocation').text(); //record.Location;
 geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
             var latitude = results[0].geometry.location.lat();
             var longitude = results[0].geometry.location.lng();
             EventLocation.center = new google.maps.LatLng(latitude, longitude);
             //onSuccessMaps(latitude,longitude);
        } else {
            alert('Fail to find location');
        }
    }); 

但在另一个函数EventLocation.center中,它不更新,它将以前的值作为('35.59214,-121.046048')。如何解决此问题?

地理代码调用是异步的,因此代码将在等待响应时继续运行。实际上,在处理响应之前,您必须将控件返回到浏览器。

这意味着任何需要坐标的方法都必须从成功回调方法中调用:

geocoder.geocode( { 'address': address}, function(results, status) {
  if (status == google.maps.GeocoderStatus.OK) {
    var latitude = results[0].geometry.location.lat();
    var longitude = results[0].geometry.location.lng();
    EventLocation.center = new google.maps.LatLng(latitude, longitude);
    // here the coordinates _are_ set
    // this is where you put the code that needs to use the coordinates
  } else {
    alert('Fail to find location');
  }
});
// here the coordinates are _not_ set yet