2010-08-25 51 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