我很难使用Google Maps API v3通过以下脚本搞清楚范围问题。我正在尝试对未知数量的记录进行地理编码(从数据库中提取)并从结果中创建PolyLine。代码中有一些红宝石,但它与JS的权利不相关吗?
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不存在,但我已确认它正在地理编码器功能中正确填充。知道为什么它不尊重全球范围吗?
答案 0 :(得分:2)
地理编码的东西将是异步。当达到drawHistoryPath(trippath)
的调用时,第一个地理编码请求可能是完成后的几毫秒!
设置包含“引脚”计数的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 %>