1

How to detect click on map outside features from two vector layers in OpenLayers 2? Here is a code that alerts on selecting feature:

var layer1 = new OpenLayers.Layer.Vector("Vector Layer 1");
var layer2 = new OpenLayers.Layer.Vector("Vector Layer 2", {
    styleMap: new OpenLayers.StyleMap({ "default": {
    'fillColor': '#669933',
    'pointRadius': 6
  }})
});
for (var i=0; i<10; i++) {
    layer1.addFeatures([new OpenLayers.Feature.Vector(
    new OpenLayers.Geometry.Point((360 * Math.random()) - 180, (180 * Math.random()) - 90)
  )]);
    layer2.addFeatures([new OpenLayers.Feature.Vector(
    new OpenLayers.Geometry.Point((360 * Math.random()) - 180, (180 * Math.random()) - 90)
  )]);
}
map.addLayers([layer1, layer2]);

var select = new OpenLayers.Control.SelectFeature([layer1, layer2], {
    onSelect: function (feature) {
    alert("selected");
  }
});
map.addControl(select);
select.activate();

Now I want to alert "all deselected" when user resets the selection.

Example: http://jsfiddle.net/f6rvj7q9/

1

You will need to listen for the Unselect event, then use a short timeout to ensure another feature hasn't been selected

var selected = false;
var select = new OpenLayers.Control.SelectFeature([layer1, layer2], {
    onSelect: function (feature) {
    selected = true;
    alert("selected");
  },
    onUnselect: function (feature) {
    selected = false;
    setTimeout(function(){ if (!selected) alert("not selected"); }, 1);
  }
});

It is also possible to listen for clicks anywhere on a map (for example if you need to make WMS GetFeatureInfo requests). See the source of this example http://dev.openlayers.org/examples/click.html

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.