简体   繁体   中英

OpenLayers on Load Markers Popup

I'm using OpenLayers to view a map and I'm having an issue with the marker's popup. When the Markers are loaded, I'm assigning them two events the moouseover and mouseout but when any of the markers are triggered with these events only the first created marker's popup is shown, even when I mouseover other markers. Its like I'm only creating these events for the first marker and not for all of them.. Any ideas? Thanks

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);
        }

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM