【问题标题】:javascript scoping issue inside a function call函数调用中的javascript范围问题
【发布时间】:2010-08-25 21:27:57
【问题描述】:

我很难使用 Google Maps API v3 找出以下脚本的范围问题。我正在尝试对未知数量的记录进行地理编码(从数据库中提取)并根据结果创建折线。代码中撒了一些红宝石,但它应该与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 不存在,但我已确认它已在地理编码器函数中正确填充。知道为什么它不尊重全局范围吗?

【问题讨论】:

    标签: javascript jquery ruby-on-rails google-maps


    【解决方案1】:

    地理编码内容将是异步。当到达对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 %>
    

    【讨论】:

    • 几乎让你成为我的英雄
    • 哈哈谢谢!好吧,祝你好运。有一天,我会用地理编码器的东西编写一些我自己的代码。
    猜你喜欢
    • 1970-01-01
    • 2011-11-13
    • 2016-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-24
    • 1970-01-01
    相关资源
    最近更新 更多