5

In my react application, I've drawn a polygon by using some points and then I'm trying to find out if mouse current location is inside the polygon or not. I'm using d3.polygonContains and passing it points array with current location points but it always returns false, although points are inside polygon.

here is an example;

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>

Can anybody tell me what I'm doing wrong here??

Naila Akbar
  • 3,033
  • 4
  • 34
  • 76
  • 1
    `let testPoint = [42.33288, -71.05835];` and `alert(d3.polygonContains(points, [42.33288, -71.05835]));` –  Sep 23 '19 at 06:21
  • Regarding the current close vote: this is not a *typo* question, since the documentation is far from clear about the first argument of `d3.polygonContains`. – Gerardo Furtado Sep 23 '19 at 06:27
  • exactly.. and I've not find any question/ answer related to this array issue.. – Naila Akbar Sep 23 '19 at 06:29

1 Answers1

6

testPoints itself must be a simple array with 2 elements, with x and y positions in that order, not an array with an inner array:

let testPoint = [42.33288, -71.05835];

Unfortunately the docs are not explicitly clear about this, it just says:

d3.polygonContains(polygon, point)

Returns true if and only if the specified point is inside the specified polygon.

But one can always inspect the 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

Here is the code with that change:

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>
Community
  • 1
  • 1
Gerardo Furtado
  • 100,839
  • 9
  • 121
  • 171