首页 > 解决方案 > 在 NodeJS 中查找 GeoJSON 点所在的多边形

问题描述

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

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

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

标签: node.jsd3.jspolygonr-treepoint-in-polygon

解决方案


对于多边形测试中的一个简单点,您可以检查turf哪个具有booleanPointInPolygon. Turf 在节点中工作,但您应该检查 v5 和 v6+ 之间关于如何相应地使用 npm 的差异。点应该是长/纬度(不是纬度/长),并且可以轻松地将多边形从要素集合的要素几何中拉出。

对于一个更复杂的用例,您有许多点和许多多边形来定位它们,您应该考虑使用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对这组减少的多边形执行测试。


推荐阅读