Search code examples
javascriptgeometryopenlayers

How to get all points inside a polygon in openlayers 4.x?


I want to integrate a feature using Openlayers 4.x is that I want to get all points inside a polygon on map. Currently I can get all coordinates of polygon itself.

But I want all coordinates or points inside of the polygon. If I explain it more that means I want all points or coordinates on the map surrounded by the polygon area.


Solution

  • Building on @willsters answer, if having identified the candidates and you are only looking for points (where the geometry is the extent) forEachFeatureIntersectingExtent could then be used in the reverse direction to see if the points intersect the polygon's geometry.

    var candidates = [];
    source.forEachFeatureIntersectingExtent(myPolygon.getGeometry().getExtent(),function(feature){
        if (feature.getGeometry().get('type') == 'Point') {
            candidates.push(feature);
        }
    });
    
    var selected = [];
    candidates.forEach(function(candidate){
        source.forEachFeatureIntersectingExtent(candidate.getGeometry().getExtent(),function(feature){
            if (feature === myPolygon) {
                selected.push(candidate);
            }
        });
    });
    

    Also for single coordinate points I think it could be done in a single step:

    var selected = [];
    source.forEachFeatureIntersectingExtent(myPolygon.getGeometry().getExtent(),function(feature){
        if (feature.getGeometry().get('type') == 'Point' &&
            myPolygon.getGeometry().intersectsCoordinate(feature.getGeometry().get('coordinates')) {
                candidates.push(selected);
        }
    });
    

    Regarding dividing into cells something like this would generate pinpush points for each cell of a 10x10 grid which contained the polygon. If only part of a cell intersected the polygon a pinpush at the center of the cell might be outside the geometry.

    var extent = myPolygon.getGeometry().getExtent();
    for (var i=extent[0]; i<extent[2]; i+=(extent[2]-extent[0])/10) {
        for (var j=extent[1]; j<extent[3]; j+=(extent[3]-extent[1])/10) {
            var cellExtent = [i,j,i+(extent[2]-extent[0])/10),j+(extent[3]-extent[1])/10];
            source.forEachFeatureIntersectingExtent(cellExtent,function(feature){
                if (feature === myPolygon) {
                   var pinPush = new ol.feature(new ol.geom.Point(ol.extent.getCenter(cellExtent)));
                   source.addFeature(pinPush); 
                }
            });
        }
    }