在javascript中更新全局变量

时间:2012-03-13 06:53:23

标签: javascript html5 google-maps

我在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')。 我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

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

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

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
相关问题