2

I am using a selectFeature control for a point layer in OpenLayers 2.12. I have a problem after removing the selectFeature control from the map.

The reason why I want to remove the control is because the target layer of the control is destroyed and a new one is added every time the map is moved.

In this process I also remove the selectFeature control from the map and add a new one for the updated layer. But that does not work properly. After the first move/zoom event of the map get the following error:

Error: getFeatureFromEvent called on layer with no renderer. This usually means you destroyed a layer, but not some handler which is associated with it.

Here is a version of the function refresh, which is called on any pan/zoom event of the map:

var mylayer;
var mycontrol;
refresh = function(){

     // Remove previous layers and controls
    if(mylayer != null){
        mylayer.destroy();
        map.removeControl(mycontrol);
    }

    // Get mylayer
    mylayer = new OpenLayers.Layer.Vector("GeoJSON", 
        ...
    );      

    // Add layer and selectFeature control
    map.addLayer(mylayer);   
    mycontrol = new OpenLayers.Control.SelectFeature(mylayer,{  
        onSelect: function(e) {
        $("#tmpOutput1").html(e.attributes.name + "\n" + e.attributes.id);
        }
    });
    map.addControl(mycontrol);  
    mycontrol.activate();   

}

UPDATE

To solve the problem I had to change the layer/control removal to this:

if(mylayer != null){
    map.removeControl(mycontrol);
    mycontrol.destroy();

    map.removeLayer(mylayer);
    mylayer.destroy();
}

Note that here the order matters (at least in my example): first remove the control, then remove the layer.

3

In my opinion there is an issue with layer removal. To my understanding the function OpenLayers.Layer.destroy() will not remove the layer from map; according to the API docs, its mission is "to alleviate cyclic references which the Javascript garbage cleaner can not take care of on its own" (http://goo.gl/LvYxD).

To remove a layer, after calling the destroy() function, you must call the function OpenLayers.Map.removeLayer() (http://goo.gl/cQmkO).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.