我正在尝试遍历一系列多边形以查看我的单个点是否存在于其中一个多边形中。从我读过的内容来看,我需要导入 topojson,将其转换为 geojson 对象,然后遍历每个多边形检查点。这是我使用 D3、Topojson 和 Turf 的结果...
const point = turf.point([long, lat]);
d3.json('data/myAreas.json').then((myAreas) => {
const keys = Object.keys(myAreas.objects);
const geo = topojson.feature(myAreas, myAreas.objects[keys[0]]);
geo.features.forEach((area) => {
const searchWithin = turf.polygon([[area.geometry.coordinates[0]]]);
const ptsWithin = turf.pointsWithinPolygon(point, searchWithin);
console.log('ptsWithin?', ptsWithin);
});
});
当它到达 const searchWithin = turf.polygon([[area.geometry.coordinates[0]]]);
时,它会抛出以下错误...
Uncaught (in promise) Error: Each LinearRing of a Polygon must have 4 or more Positions.
我试过 D3 的 d3.geoContain()
但它每次都抛出 false
。我愿意接受替代解决方案,这些解决方案将检查纬度/经度坐标是否在 topojson 形状内。谢谢。
最佳答案
这就是最终对我有用的方法,将 turf.polygon()
替换为 turf.multiPolygon
const point = turf.point([long, lat]);
d3.json('data/myAreas.json').then((areas) => {
const keys = Object.keys(areas.objects);
const geo = topojson.feature(areas, areas.objects[keys[0]]);
geo.features.forEach((k, i) => {
const searchWithin = turf.multiPolygon([[k.geometry.coordinates[0]]]);
const ptsWithin = turf.pointsWithinPolygon(point, searchWithin);
if (ptsWithin.features.length > 0) {
console.log('ptsWithin?', i, ptsWithin); // The index of the containing polygon
console.log(geo.features[i]); // The features for the corresponding polygon
}
});
});
关于D3.js 与 Turf.js 错误 : "Uncaught (in promise) Error: Each LinearRing of a Polygon must have 4 or more Positions.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52024526/