在 NodeJS 中查找 GeoJSON 点所在的多边形

问题描述

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

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

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

解决方法

对于多边形测试中的一个简单点,您可以检查具有 turfbooleanPointInPolygon。 Turf 在 node 中工作,但您应该检查 v5 和 v6+ 之间关于如何相应地使用 npm 的差异。点应该是 long/ lat(不是纬度/经度)并且多边形可以 easily pulled 超出您的要素集合的要素几何。

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

请注意,rbush 库根据多边形的边界框构建了一个 r 树,而不是多边形本身,因此使用 r 树只是一种大大减少需要测试的多边形数量的方法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 测试。

,

我使用库 polygon-lookup

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...