我正在使用带有Waze(地图图层)的OpenLayers,并且由于无法传播变量而遇到了一些问题。
我有以下代码:

    var lonlat = new Array(), infodiv = new Array();

    for (var i = 0; i < stations.length; i++)
    {
        if (i == 0)
            icon_temp = icon;
        else
            icon_temp = icon.clone();

        lonlat[i] = new OpenLayers.LonLat(stations[i].lon,stations[i].lat);
        infodiv[i] = "<div style='font-size: 14px;'><strong>" + stations[i].company + "</strong></div>";

        marker = new OpenLayers.Marker(lonlat[i],icon_temp);
        marker.setOpacity(0.8);

        marker.events.register('mousedown', marker, function(evt) {
            popup = new OpenLayers.Popup.FramedCloud(null,
                               lonlat[i],
                               null,
                               infodiv[i],
                               anchor=null,true,null);

            map.addPopup(popup);

            OpenLayers.Event.stop(evt);

        });

        markers.addMarker(marker);
    }


代码应遍历“ stations”数组,并在地图上添加标记。它很好用!

问题出在“ lonlat”和“ infodiv”数组上。 “ OpenLayers.Popup.FramedCloud”看不到它们-返回空值(使用FireBug检查)。如果我丢失数组,并且每次仅分配lonlat = ...和infodiv = ...,则如下所示:

    for (var i = 0; i < stations.length; i++)
    {
        if (i == 0)
            icon_temp = icon;
        else
            icon_temp = icon.clone();

        lonlat = new OpenLayers.LonLat(stations[i].lon,stations[i].lat);
        infodiv = "<div style='font-size: 14px;'><strong>" + stations[i].company + "</strong></div>";

        marker = new OpenLayers.Marker(lonlat,icon_temp);
        marker.setOpacity(0.8);

        marker.events.register('mousedown', marker, function(evt) {
            popup = new OpenLayers.Popup.FramedCloud(null,
                               lonlat,
                               null,
                               infodiv,
                               anchor=null,true,null);

            map.addPopup(popup);

            OpenLayers.Event.stop(evt);

        });

        markers.addMarker(marker);
    }


它被传播到FrameCloud函数并被显示-但问题是它仅显示最后一个lonlat和infodiv(就像它不保存它们的副本,而是保存实际的对象-因此每次迭代“ lonlat”和“ infodiv”已被最新信息取代)。

如何克服?

最佳答案

这是由于变量i的关闭。

引入另一个范围,例如

(function(i){
marker.events.register('mousedown', marker, function(evt) {
                    popup = new OpenLayers.Popup.FramedCloud(null,
                                       lonlat[i],
                                       null,
                                       infodiv[i],
                                       anchor=null,true,null);

                    map.addPopup(popup);

                    OpenLayers.Event.stop(evt);

                });
})(i);

10-06 04:22