0

我正在使用 OpenLayers 查看地图,但我遇到了标记弹出窗口的问题。加载标记时,我为它们分配了两个事件mouseover 和mouseout,但是当这些事件触发任何标记时,即使我将鼠标悬停在其他标记上,也只会显示第一个创建的标记的弹出窗口。就像我只是为第一个标记而不是为所有标记创建这些事件..有什么想法吗?谢谢

var listMarkers = getMarkers();

        for (var i = 0; i < listMarkers.length; i++) {
            var size = new OpenLayers.Size(21, 25);
            var offset = new OpenLayers.Pixel(-(size.w / 2), -size.h);
            var icon;
            if (listMarkers[i].Icon.trim() === "red") {
                icon = new OpenLayers.Icon
                ('http://www.openlayers.org/dev/img/marker.png', size, offset);
            }
            else {
                icon = new OpenLayers.Icon
                ('http://www.openlayers.org/dev/img/marker-' + listMarkers[i].Icon.trim() + '.png', size, offset);
            }

            var mark = new OpenLayers.Marker(new OpenLayers.LonLat(listMarkers[i].Longitude,
                listMarkers[i].Latitude).transform(new OpenLayers.Projection("EPSG:4326"),
            map.getProjectionObject()), icon);

            //here add mouseover event
            mark.events.register('mouseover', mark, function (evt) {
                popup = new OpenLayers.Popup.FramedCloud("Popup",
                    new OpenLayers.LonLat(listMarkers[i].Longitude,
                listMarkers[i].Latitude).transform(new OpenLayers.Projection("EPSG:4326"),
            map.getProjectionObject()),
                    null,
                    '<div><b>' + listMarkers[i].Title + '</b><br/>' + listMarkers[i].Description + '</div>',
                    null,
                    false);
                map.addPopup(popup);
            });
            //here add mouseout event
            mark.events.register('mouseout', mark, function (evt) { popup.hide(); });
            markers.addMarker(mark);
        }
4

1 回答 1

0

In the mouseover event while creating popup you're referring to listMarkers[i], which in javascript scope would remember last value of given variable i, so for every popup it would get information from listMarkers[listMarkers.length-1]. To fix this, add details (Title, Latitude, Longitude) into the mark object (mark.data.Title = listMarkers[i]), and then read them in event handler from evt or this object (as you're setting it in register call).

于 2013-05-06T21:37:28.263 回答