2010-08-25 30 views
1

我很難用下面的使用Google Maps API v3的腳本來確定範圍問題。我試圖對未知數量的記錄(從數據庫中提取)進行地理編碼,並從結果中創建一個PolyLine。代碼中有些紅寶石,但它不應該與JS的權利相關?函數調用內的JavaScript範圍問題

var trippath = new Array(); 

function drawHistoryPath(coordinates) { 
var tripHistoryPath = new google.maps.Polyline({ 
    map: map, 
    path: coordinates, 
    strokeColor: "#6A0606", 
    strokeOpacity: 1.0, 
    strokeWeight: 5 
}); 
} 

<% @pins.each do |ps| %> 
     geocoder.geocode({ 'address': '<%= escape_javascript(ps.location) %>'}, function(results, status) { 
      if (status == google.maps.GeocoderStatus.OK) { 
      trippath.push(results[0].geometry.location); 
      } else { 
      alert("Geocode was not successful finding <%= escape_javascript(ps.location) %> for the following reason: " + status); 
      } 
     }); 
<% end %> 
drawHistoryPath(trippath); 

當drawHistoryPath被調用,trippath不存在,但我已經證實,它正在正確填充的地理編碼器函數內。任何想法爲什麼它不尊重全球範圍?

回答

2

該地理編碼的東西將是異步。當到達drawHistoryPath(trippath)的呼叫時,第一個地理編碼請求可能會在完成後數毫秒內完成!

設置一個包含「pins」數量的Javascript變量。讓你的代碼在回調(到地理編碼)中遞減計數器。當計數器爲零時,您會知道是時候致電drawHistoryPath。您將在裏面撥打這個地理編碼回調函數。

var pinCount = <% @pins.length %>; // making this up because I don't know Rails/Ruby/whatever 

<% @pins.each do |ps| %> 
    geocoder.geocode({ 'address': '<%= escape_javascript(ps.location) %>'}, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
     trippath.push(results[0].geometry.location); 
     if (!--pinCount) 
      drawHistoryPath(trippath); 
     } else { 
     alert("Geocode was not successful finding <%= escape_javascript(ps.location) %> for the following reason: " + status); 
     } 
    }); 
<% end %> 
+0

非常多讓你成爲我的英雄 – Ryan 2010-08-25 21:45:01

+0

哈哈謝謝!好吧,祝你好運。其中一天,我會用地理編碼器的東西寫一些我自己的代碼。 – Pointy 2010-08-25 21:51:03