我很难通过使用 Google Maps API v3 的以下脚本找出范围界定问题。我正在尝试对未知数量的记录(从数据库中提取)进行地理编码并根据结果创建折线。代码中有一些 ruby ,但它不应该与 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 不存在,但我已确认它已在地理编码器函数中正确填充。知道为什么它不遵守全局范围吗?
最佳答案
地理编码将异步。当到达对 drawHistoryPath(trippath)
的调用时,第一个地理编码请求可能距离完成还有很多毫秒!
设置一个包含“pin”计数的 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 %>
关于函数调用中的 javascript 作用域问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3570352/