在 NodeJS 中查找 GeoJSON 点位于哪个多边形

Find in which polygon a GeoJSON point lies in, in NodeJS

给定一个已定义的 (lat, lon) 地理点,我试图找到该点所在的多边形。我想遍历所有多边形效率不高。是否有可用的 NodeJS 函数或库来执行此操作?

const polygon = getPolygonFromPoint(FeatureCollection, x, y);

没有重叠的多边形,实际上我是用它来检测定义的GPS坐标点位于某个国家/地区的哪个地区。

我用库实现了 polygon-lookup

const PolygonLookup = require('polygon-lookup')
const featureCollection = {
    type: 'FeatureCollection',
    features: [{
        type: 'Feature',
        properties: { id: 'bar' },
        geometry: {
            type: 'Polygon',
            coordinates: [ [ [ 0, 1 ], [ 2, 1 ], [ 3, 4 ], [ 1, 5 ] ] ]
        }
    }]
}
var lookup = new PolygonLookup(featureCollection)
var poly = lookup.search(1, 2)
console.log(poly.properties.id) // bar

对于多边形测试中的一个简单点,您可以检查 turf which has a booleanPointInPolygon. Turf works in node but you should check for differences between v5 and v6+ around how to use npm accordingly. Points should be (not lat/ long) and the polygon can be 要素集合的要素几何。

对于更复杂的用例,您有许多点和许多要在其中定位它们的多边形,您应该考虑使用 rbush

请注意,rbush 库根据多边形的边界框而不是多边形本身构建了一个 r-tree,因此使用 r-tree 只是一种大大减少您需要的多边形数量的方法用 booleanPointInPolygon.

测试

rbush 的示例代码:

const RBush = require("rbush");
const turfBbox = require("@turf/bbox").default;

const geo = {} // your feature collection...
const maxEntriesPerNode = 50; // check the doco
const tree = new RBush(maxEntriesPerNode);
const bbox2Object = (keys, bbox) => ["minX", "minY", "maxX", "maxY"].reduce((o, k, i) => ({...o, [k]: bbox[i]}), {})

// create rtree from feature collection
geo.features.forEach(feature => {
  const leaf = bbox2Object(bboxKeys, turfBbox(feature)); // use bbox of feature
  leaf["id"] = feature.properties.SOME_ID; // add some custom properties
  tree.insert(leaf);
});

// test a random point from your data
const [x, y] = [123, 456]; // should be long, lat
const test = tree.search({minX: x, minY: y, maxX: x, maxY: y});
// test should have an array of leaves per the tree.insert above

然后您可以对这组减少的多边形执行 booleanPointInPolygon 测试。