在我的react application中,我通过使用一些点绘制了polygon,然后试图找出鼠标当前位置是否在多边形内。我正在使用d3.polygonContains并将其与当前位置点一起传递给点数组,但是尽管点位于多边形内,但它始终返回false。

这是一个例子;



let points = [
            [ 42.34624, -71.06024 ],
            [ 42.33558, -71.06616 ],
            [ 42.32632, -71.05835 ],
            [ 42.32987, -71.05428 ],
            [ 42.34732, -71.05432 ],
            [ 42.34618, -71.05973 ],
            [ 42.34624, -71.06024 ]
        ];

let testPoint = [
    [42.33288, -71.05835]

];
alert(d3.polygonContains(points, testPoint));

alert(d3.polygonContains(points, (42.33288, -71.05835)));

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>





有人可以告诉我我在做什么错吗?

最佳答案

testPoints本身必须是一个具有2个元素的简单数组,并依次排列xy位置,而不是具有内部数组的数组:

let testPoint = [42.33288, -71.05835];


不幸的是,docs对此并不清楚,只是说:


  d3.polygonContains(多边形,点)
  
  当且仅当指定点在指定多边形内时才返回true。


但是总是可以检查source code

export default function(polygon, point) {
  var n = polygon.length,
      p = polygon[n - 1],
      x = point[0], y = point[1],
      //^-- here we see that 'point' is an array with 2 elements


这是具有此更改的代码:



let points = [
  [42.34624, -71.06024],
  [42.33558, -71.06616],
  [42.32632, -71.05835],
  [42.32987, -71.05428],
  [42.34732, -71.05432],
  [42.34618, -71.05973],
  [42.34624, -71.06024]
];

let testPoint = [42.33288, -71.05835];

console.log(d3.polygonContains(points, testPoint));
console.log(d3.polygonContains(points, [42.33288, -71.05835]));

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

09-25 17:45