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



给定一个定义的(lat, lon)地理点,我试图找到该点所在的多边形。我认为迭代所有多边形是无效的。NodeJS有什么函数或库可以做到这一点吗?

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

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

对于多边形测试中的一个简单点,您可以检查具有booleanPointInPolygonturf。Turf在节点中工作,但您应该检查v5和v6+之间关于如何相应地使用npm的差异。点应该是长/长(而不是长/长(,并且多边形可以很容易地从要素集合的要素几何图形中拉出。

对于一个更复杂的用例,其中有许多点和许多多边形可以在其中定位它们,您应该考虑使用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, 1 ], [ 3, 4 ], [ 1, 5 ] ] ]
}
}]
}
var lookup = new PolygonLookup(featureCollection)
var poly = lookup.search(1, 2)
console.log(poly.properties.id) // bar

最新更新