问题
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??
回答1:
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>
来源:https://stackoverflow.com/questions/58056453/d3-polygoncontains-always-returns-false