thi*_*nom 6 javascript geometry geolocation
我有3个点(lat,lon)形成一个三角形.我怎么能找到一个点是否在这个三角形内?
小智 5
Java代码只是三角形,即3分.
public static boolean pntInTriangle(double px, double py, double x1, double y1, double x2, double y2, double x3, double y3) {
double o1 = getOrientationResult(x1, y1, x2, y2, px, py);
double o2 = getOrientationResult(x2, y2, x3, y3, px, py);
double o3 = getOrientationResult(x3, y3, x1, y1, px, py);
return (o1 == o2) && (o2 == o3);
}
private static int getOrientationResult(double x1, double y1, double x2, double y2, double px, double py) {
double orientation = ((x2 - x1) * (py - y1)) - ((px - x1) * (y2 - y1));
if (orientation > 0) {
return 1;
}
else if (orientation < 0) {
return -1;
}
else {
return 0;
}
}
Run Code Online (Sandbox Code Playgroud)
下面是这里讨论的重心坐标解决方案的 Javascript 实现:
// Returns true if point P inside the triangle with vertices at A, B and C
// representing 2D vectors and points as [x,y]. Based on
// http://www.blackpawn.com/texts/pointinpoly/default.html
function pointInTriange(P, A, B, C) {
// Compute vectors
function vec(from, to) { return [to[0] - from[0], to[1] - from[1]]; }
var v0 = vec(A, C);
var v1 = vec(A, B);
var v2 = vec(A, P);
// Compute dot products
function dot(u, v) { return u[0] * v[0] + u[1] * v[1]; }
var dot00 = dot(v0, v0);
var dot01 = dot(v0, v1);
var dot02 = dot(v0, v2);
var dot11 = dot(v1, v1);
var dot12 = dot(v1, v2);
// Compute barycentric coordinates
var invDenom = 1.0 / (dot00 * dot11 - dot01 * dot01);
var u = (dot11 * dot02 - dot01 * dot12) * invDenom;
var v = (dot00 * dot12 - dot01 * dot02) * invDenom;
// Check if point is in triangle
return (u >= 0) && (v >= 0) && (u + v < 1);
}
Run Code Online (Sandbox Code Playgroud)
据说它比基于跨产品的解决方案更快。