函数调用中的javascript作用域问题
使用GoogleMapsAPIv3,我很难找出以下脚本的作用域问题。我试图对未知数量的记录(从数据库中提取)进行地理编码,并根据结果创建一条多段线。代码中有一些ruby,但它不应该与JS相关,对吗函数调用中的javascript作用域问题,javascript,jquery,ruby-on-rails,google-maps,Javascript,Jquery,Ruby On Rails,Google Maps,使用GoogleMapsAPIv3,我很难找出以下脚本的作用域问题。我试图对未知数量的记录(从数据库中提取)进行地理编码,并根据结果创建一条多段线。代码中有一些ruby,但它不应该与JS相关,对吗 var trippath = new Array(); function drawHistoryPath(coordinates) { var tripHistoryPath = new google.maps.Polyline({ map: map, path: coordinat
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);
var trippath=new Array();
函数drawHistoryPath(坐标){
var tripHistoryPath=新建google.maps.Polyline({
地图:地图,
路径:坐标,
strokeColor:#6A0606“,
笔划不透明度:1.0,
冲程重量:5
});
}
geocoder.geocode({'address':''},函数(结果,状态){
if(status==google.maps.GeocoderStatus.OK){
trippath.push(结果[0].geometry.location);
}否则{
警报(“地理代码由于以下原因未成功查找:“+状态”);
}
});
drawHistoryPath(trippath);
调用drawHistoryPath时,trippath不存在,但我已确认它在geocoder函数中正确填充。知道为什么它不尊重全球范围吗?地理编码将是异步的。当到达对
drawHistoryPath(trippath)
的调用时,第一个地理编码请求可能离完成还有很多毫秒
设置包含“pins”计数的Javascript变量。将代码放在回调(到地理代码)中,减少该计数器。当计数器为零时,您将知道是时候调用drawHistoryPath
。您将把该调用放在geocode回调函数中
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 %>
var pinCount=;//因为我不懂Rails/Ruby/什么,所以编造了这个
geocoder.geocode({'address':''},函数(结果,状态){
if(status==google.maps.GeocoderStatus.OK){
trippath.push(结果[0].geometry.location);
如果(!--pinCount)
drawHistoryPath(trippath);
}否则{
警报(“地理代码由于以下原因未成功查找:“+状态”);
}
});
你真是我的英雄哈,谢谢!祝你好运。总有一天我会用地理编码器的东西写一些我自己的代码。