【问题标题】:GMaps JS Geocode: Using/Passing Variables With Asynchronous Geocode Function?GMaps JS 地理编码:使用/传递具有异步地理编码功能的变量?
【发布时间】:2012-05-11 16:20:09
【问题描述】:

我有一个位置对象的数组列表,我正在使用其中的一些来构建一个完整的地址,然后对其进行地理编码。一旦我收到 OK 状态,我就会在地图上放置一个标记。这一切都很好。但是,现在我还想在每个标记上放置一个信息窗口,其中包含我的数组列表 LocationName 中的另一个属性。 代码在这里:

function placeMarkers(myObjList){
var geocoder = new google.maps.Geocoder();
for(var i=0; i<myObjList.length; i++){
    var fullAddress = myObjList[i].Address + ", " + myObjList[i].City + ", " + myObjList[i].State + ", " + myObjList[i].Zip;
    /* The variable I would like to have access to in the geocode call */
    var locationName = myObjList[i].LocationName;

    geocoder.geocode( { 'address': fullAddress}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            alert(locationName);
            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location,
                clickable: true
            });
            markers.push(marker);
        } else {
            alert("Geocode was not successful for the following reason: " + status);
        }
    });
}
}

当我获得 OK 状态时,警报只是查看 locationName 是什么。但是在测试中它总是相同的值。一旦我可以对其进行调整以每次都反映正确的值,然后我就会排列代码以将信息窗口放置在标记上。

任何帮助将不胜感激!

【问题讨论】:

    标签: javascript google-maps asynchronous geocode


    【解决方案1】:

    最简单的事情可能是在循环中创建一个本地范围块,以便每次添加委托/匿名函数进行地理编码时, locationName 实际上引用一个 不同 变量。将 var 放在循环中不会创建变量的新实例,var 声明本质上会移动到封闭范围块的顶部。

    for(var i=0; i<myObjList.length; i++){
        var fullAddress = myObjList[i].Address + ", " + myObjList[i].City + ", " + myObjList[i].State + ", " + myObjList[i].Zip;
        //begin scope block
        (function(){
            var locationName = myObjList[i].LocationName;
            var yourObject = myObjList[i];
             //etc.
            geocoder.geocode( ...);
        //end scope block
        })();
    }
    

    编辑:

    或者,如果您使用某个框架/允许您传递匿名函数来为数组中的每个项目执行代码,那么您会自动处理此类范围问题。

    【讨论】:

    • 我仍然对这个概念感到困惑@.@
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-27
    • 1970-01-01
    相关资源
    最近更新 更多