2012-03-13 102 views
0

我在JavaScript中有像更新全局变量在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')。 我该如何解决这个问题?

+0

凡EventLocation被定义?在函数或顶级脚本文件/标签内? – Nathan 2012-03-13 06:58:09

+0

您是否尝试将中心属性从开始更改为Google地图latlng对象? – 2012-03-13 07:00:02

+0

尝试'window.EventLocation.center = new google.maps.LatLng(latitude,longitude);' – Nemoy 2012-03-13 07:00:04

回答

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 
+0

@伊拉:这是一样的。 Javascript是严格单线程的,所以一次只能运行一种方法。在成功回调可以运行之前,您必须退出所有其他方法。任何需要从地理编码调用返回的坐标的代码都必须进入回调。我在上面添加了一些代码。 – Guffa 2012-03-13 07:22:23

+0

@Ila:没有任何东西可以保持全局更新值。您只是在设置之前尝试使用它。 – Guffa 2012-03-13 08:16:23

+0

@Ila:你把代码放在回调里面了吗? – Guffa 2012-03-13 08:27:25