我试图遍历一系列多边形,以查看我的单点是否存在于这些多边形中。从我读过的书中,我需要导入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形状内。谢谢。
答案 0 :(得分:1)
这就是最终为我工作的原因,将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
}
});
});
答案 1 :(得分:0)
我遇到了同样的错误。
后来我发现我没有将要呈现的数组完全嵌套到turf.polygon()。
从上面的示例中摘录以下行
const searchWithin = turf.polygon([[area.geometry.coordinates[0]]]);
我认为这应该是(请注意额外的[]括号):
const searchWithin = turf.polygon([[[area.geometry.coordinates[0]]]]);
这是来自turfjs网站的示例:
var poly = turf.polygon([[[0,29],[3.5,29],[2.5,32],[0,29]]]);