繁体   English   中英

如何在 openlayers 4.x 中获取多边形内的所有点?

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

我想使用 Openlayers 4.x 集成一个功能是我想获取地图上多边形内的所有点。 目前我可以获得多边形本身的所有坐标。

但我想要多边形内的所有坐标或点。 如果我解释得更多,那意味着我希望地图上的所有点或坐标都被多边形区域包围。

基于@willsters 的回答,如果已经确定了候选者并且您只是在寻找点(其中几何是范围) forEachFeatureIntersectingExtent 可以在相反的方向使用,以查看这些点是否与多边形的几何相交。

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);
        }
    });
});

同样对于单个坐标点,我认为可以一步完成:

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);
    }
});

关于划分单​​元格,这样的事情将为包含多边形的 10x10 网格的每个单元格生成 pinpush 点。 如果只有部分单元格与多边形相交,单元格中心的推压可能会超出几何图形。

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); 
            }
        });
    }
}

使用vectorSource.forEachFeatureIntersectingExtent()polygonGeom.getExtent() 这将为您提供大多数情况下的范围快捷方式。 之后,您将需要自己实现点入多边形(在线上有很多来源)或使用像https://github.com/bjornharrtell/jsts这样的库。 OpenLayers 仅提供与范围的几何交集。

我经常将 turf.js 库与专门用于此类任务的 openlayers 一起包含在内。 我的大部分几何图形都是 geojson 中的 nativley,所以 turf.js 非常适合。 如果您有 geojson FeatureCollection。 您可以迭代 .features 数组(甚至只是[x, y]点的任何数组)并检查每个数组以查看它是否在您的多边形内。 如果有帮助,我可以制作一个工作小提琴。

// In this example I'm looking for all features
// that have AT LEAST ONE point within  
// the world extent (WGS84)
const polygon = turf.bboxPolygon([-180, -90, 180, 90])
myGeoJson.features.forEach(function(feature){
    const points = turf.explode(feature);
    const pointsWithin = turf.pointsWithinPolygon(points, polygon);
    if(pointsWithin.features && pointsWithin.features.length){
        // feature has AT LEAST ONE point inside the polygon
        // I can see what points by iterating the
        // pointsWithin.features array
    }else{
        // feature has ZERO points inside the polgyon
    }
});

http://turfjs.org/docs#pointsWithinPolygon

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM