2012-03-13 98 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