I went through many similar questions on Stackoverflow and other websites and I based my solution on those answers but I still can't get it to work…
My problem: I want to determine whether or not a certain GPS location P
lies within a rectangular area bounded by four given GPS coordinates A
, B
, C
, D
.
At the moment I am calculating the areas of triangles ABP
, BCP
, CDP
and DAP
. If any of those areas is bigger than zero (don't be upset, mathematicians) the point lies outside my rectangle as explained here.
Code:
private static double triangleArea(Location a, Location b, Location c) {
// (C.x*B.y-B.x*C.y)-(C.x*A.y-A.x*C.y)+(B.x*A.y-A.x*B.y)
double result = (c.getLongitude()*b.getLatitude()-b.getLongitude()*c.getLatitude())-(c.getLongitude()*a.getLatitude()-a.getLongitude()*c.getLatitude())+(b.getLongitude()*a.getLatitude()-a.getLongitude()*b.getLatitude());
return result;
}
public static boolean isInsideSquare(Location a, Location b, Location c, Location d, Location p) {
if (triangleArea(a,b,p)>0 || triangleArea(b,c,p)>0 || triangleArea(c,d,p)>0 || triangleArea(d,a,p)>0) {
return false;
}
return true;
}
But when I call this function it's always returning false
. Even when using the following coordinates (latitude, longitude):
A: (50.884706, 4.714151)
B: (50.884944, 4.716149)
C: (50.884679, 4.716228)
D: (50.884441, 4.714230)
P: (50.884538, 4.714615)
Yet when I plot those points on a map (e.g. here) I can see that point P lies within ABCD… (see below)
I've read some easy solutions where you just subtract the x, y coordinates of your points, but that would obviously only work for rectangles parallel to the x-axis and y-axis, whereas my rectangle can be oriented in any angle.
Can anyone tell me what I am doing wrong or suggest a better solution to solve this problem?
Thanks a lot!