最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Strange behavior of marker events in OpenLayer - Stack Overflow

programmeradmin1浏览0评论

I have markers layer on my map.

Every time I add a new marker I register it to a mouse-click event:

var lonlat = new OpenLayers.LonLat(lon,lat);
var marker = new OpenLayers.Marker(lonlat,icon);
marker.id = callId;

marker.events.register("mousedown", marker, function() {AddPopup(marker.id);});

callMarkers.addMarker(marker);

Sometimes I want to disable/enable the event. so I use these functions:

function EnableAllMarkers()
{ 
    for (var i in callMarkers.markers)
    {
        callMarkers.markers[i].events.remove("mousedown");               

        callMarkers.markers[i].events.register("mousedown", callMarkers.markers[i],   

        function() { AddPopup(callMarkers.markers[i].id); });
    }  
}


function DisableAllMarkers()
{ 
    for (var i in callMarkers.markers)
    {
        callMarkers.markers[i].events.remove("mousedown");
    }  
}

When I use this code I get strange behavior - sometimes a popup opens for the wrong marker.

I click on marker X and popup Y opens.

Can someone help me, please?

Note:
The reason EnableAllmMarkers first removes the event is because we don't know if DisableAllmMarkers was ever called since a new marker was added. if it was called indeed, remove function will do nothing.

I have markers layer on my map.

Every time I add a new marker I register it to a mouse-click event:

var lonlat = new OpenLayers.LonLat(lon,lat);
var marker = new OpenLayers.Marker(lonlat,icon);
marker.id = callId;

marker.events.register("mousedown", marker, function() {AddPopup(marker.id);});

callMarkers.addMarker(marker);

Sometimes I want to disable/enable the event. so I use these functions:

function EnableAllMarkers()
{ 
    for (var i in callMarkers.markers)
    {
        callMarkers.markers[i].events.remove("mousedown");               

        callMarkers.markers[i].events.register("mousedown", callMarkers.markers[i],   

        function() { AddPopup(callMarkers.markers[i].id); });
    }  
}


function DisableAllMarkers()
{ 
    for (var i in callMarkers.markers)
    {
        callMarkers.markers[i].events.remove("mousedown");
    }  
}

When I use this code I get strange behavior - sometimes a popup opens for the wrong marker.

I click on marker X and popup Y opens.

Can someone help me, please?

Note:
The reason EnableAllmMarkers first removes the event is because we don't know if DisableAllmMarkers was ever called since a new marker was added. if it was called indeed, remove function will do nothing.

Share Improve this question edited Apr 4, 2021 at 17:21 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Jan 29, 2011 at 13:37 Day_DreamerDay_Dreamer 3,3738 gold badges36 silver badges61 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

This is a classic JavaScript trap: you're instantiating functions as event handlers in a loop, and the functions refer to a local variable. The problem is that all of them refer to the same local variable: the same, single, unique, only-one-place-in-memory variable. The variable in this case is "i".

At the end of that for loop, "i" will have the value of the last key in the object (and, by the way, if callMarkers.markers is really an array, then this shouldn't be a for ... in loop anyway, but that's a separate issue). When those events finally fire, therefore, all the handlers will do their thing with "i" equal to that one same key.

To fix:

  for (var i in callMarkers.markers)
    {
        callMarkers.markers[i].events.remove("mousedown");               

        callMarkers.markers[i].events.register(
          "mousedown", 
          callMarkers.markers[i],
          (function(ii) {
            return function() {
              AddPopup(callMarkers.markers[ii].id);
            }
          )(i)
         );
    } 

That introduces an intermediary anonymous function. That function is immediately called, and passed the current value of "i". By doing that — passing "i" as an argument to the anonymous function — the value is "captured" in the argument "ii". Each loop iteration will cause another invocation of the anonymous function, and the function it returns (the actual handler) will have access to its own private "ii" variable.

There are some other ways to achieve the same thing, but they're all just variations on this theme.

I had the same issue, once the event is registered to a specific Maker it triggers for all the other Marker's as well. Finally, I was able to solve it. I had to register seperate events for each marker. Following is my code:

    var makerCount=0; // I want only 2 Markers to be shown : Source,Destination

function setMarkers(x,y){
    var icon = new OpenLayers.Icon('http://www.openlayers/dev/img/marker.png',size,offset);  

 if(makerCount<2){

    if(makerCount==0){  // Source
       var location = new OpenLayers.LonLat(x,y); 

       var size = new OpenLayers.Size(21,25);
       var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);

        var sourceMarker=new OpenLayers.Marker(location,icon)
        sourceMarker.events.register('mousedown', sourceMarker, function(evt) { 
                alert('Source :: X='+ x + ' , Y=' + y); 
                OpenLayers.Event.stop(evt); }); 


        markers.addMarker(sourceMarker); 
        markers.setOpacity(0.2);
        makerCount++;
    }else{ // Destination

        var location = new OpenLayers.LonLat(x,y); 

        var size = new OpenLayers.Size(21,25);
        var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
        var halfIcon = icon.clone();  

        var destinationMarker=new OpenLayers.Marker(location,halfIcon)
        destinationMarker.events.register('mousedown', destinationMarker, function(evt) { 
                alert('Destination :: X='+ x + ' , Y=' + y); 
                OpenLayers.Event.stop(evt); 
           });          
        markers.addMarker(destinationMarker); 
        halfIcon.setOpacity(0.5);
        makerCount++;
    }

 }
}
发布评论

评论列表(0)

  1. 暂无评论