D3.js with Turf.js error: "Uncaught (in promise) Error: Each LinearRing of a Polygon must have 4 or more Positions."

D3.js with Turf.js error: "Uncaught (in promise) Error: Each LinearRing of a Polygon must have 4 or more Positions."

我正在尝试遍历一系列多边形以查看我的单个点是否存在于其中一个多边形中。从我读过的内容来看,我需要导入 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。我愿意接受替代解决方案,这些解决方案将检查 lat/lng 坐标是否在 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
    }
  });
});

我遇到了同样的错误。

我后来发现我没有充分嵌套我呈现给 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]]]);