Search code examples
openlayersopenlayers-3

Drawing a polygon to select features, but is inaccurate [OL3]


Drawing a polygon and selecting features via it:

draw.on('drawend', function(event) {

delaySelectActivate();
selectedFeatures.clear();

var polygon = event.feature.getGeometry();
var features1 = vectorSource.getFeatures();


for (var i = 0 ; i < features1.length; i++){
  if(polygon.intersectsExtent( features1[i].getGeometry().getExtent() )){
    selectedFeatures.push(features1[i]);
  }
} 
});  

Returns this result: Inaccurate polygon For some reason, Spain is selected as well, even tho it seems well off the polygon's extent? Here's an example with the dragbox selection: hand drawn rect

And here's the relevant dragbox js:

dragBox.on('boxend', function() {
    // features that intersect the box are added to the collection of
    // selected features
    drawingSource.clear();
    var extent = dragBox.getGeometry().getExtent();
    vectorSource.forEachFeatureIntersectingExtent(extent, function(feature) {
      selectedFeatures.push(feature);
    });
});

What I've tried:

  • Instead of using a for loop to get intersection (the for loop should be more accurate, but it isn't), I've tried to do it the same way like with the dragbox - with forEachFeatureIntersectingExtent. It works, but the result is the same.

I think it's because the extent of the drawn polygon is inaccurate. But then how is the extent of the features, which seem to be also polygons are accurate when using the dragbox?

I followed this tutorial: Selecting features by drawing polygons in openLayers 3


Solution

  • It seems that it's indeed much more accurate with the forEachFeatureIntersectingExtent method:

    draw.on('drawend', function(event) {
    
        delaySelectActivate();
        selectedFeatures.clear();
    
        var polygon = event.feature.getGeometry();
        vectorSource.forEachFeatureIntersectingExtent(polygon.getExtent(), function(feature) {
            selectedFeatures.push(feature);
        });    
    });  
    

    I guess the author of the tutorial used the for loop since he was intersecting points instead of vectorSource.