1

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

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

4

3 回答 3

3

在@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 点。如果只有部分单元格与多边形相交,则单元格中心的 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); 
            }
        });
    }
}
于 2018-09-26T23:17:34.053 回答
2

我经常在 openlayers 旁边包含 turf.js 库,专门用于此类任务。我的大部分几何图形都是 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

于 2018-09-26T13:24:45.877 回答
1

vectorSource.forEachFeatureIntersectingExtent()与 一起使用polygonGeom.getExtent()。这将为您提供其中大多数的范围快捷方式。之后,您将需要自己实现 point-in-poly(网上有很多资源)或使用像https://github.com/bjornharrtell/jsts这样的库。OpenLayers 仅提供与范围的几何交集。

于 2018-09-26T00:53:08.030 回答