Reputation: 17574
I a coordinate and I need to know if it is inside a square. To achieve this I am given the NorthEast and SouthWest coordinates of this square.
So far I came up with the following code:
const isInsideSquare = (center, northEast, southWest) =>
southWest.lat < center.lat &&
northEast.lat > center.lat &&
northEast.lng < center.lng &&
southWest.lng > center.lng;
However, this code fails with the following example:
const northEast = {lat: 42.1539732831, lng: -4.7027107182};
const southWest = {lat: 36.8340642391, lng: -11.5965440996};
const coord = {lat: 38.7223, lng: -9.1393};
console.log(isInsideSquare(coord, northEat, southWest)); //false
The problem is that my function returns false, instead of true. As you can see, the coord
is inside the square:
https://www.darrinward.com/lat-long/?id=59e70fdf5c8578.99150744
But somehow I am missing it.
What is wrong in my code?
Upvotes: 1
Views: 912
Reputation: 12637
on the longitude you deal with a circle, and your angles wrap around, you have to deal with that, or normalizing it somehow
const normalizeDegrees = v => v < 0 ? 360 + v % 360 : v % 360;
const isInsideSquare = (center, northEast, southWest) => (
southWest.lat < center.lat &&
northEast.lat > center.lat &&
normalizeDegrees(center.lng - southWest.lng) < normalizeDegrees(northEast.lng - southWest.lng));
const northEast = {
lat: 42.1539732831,
lng: -4.7027107182
};
const southWest = {
lat: 36.8340642391,
lng: -11.5965440996
};
const coord = {
lat: 38.7223,
lng: -9.1393
};
console.log(isInsideSquare(coord, northEast, southWest));
.as-console-wrapper{top:0;max-height:100%!important}
center is less degrees to the east of southwest than northEast is.
Upvotes: 0
Reputation: 2163
Should be
const isInsideSquare = (center, northEast, southWest) =>
southWest.lat < center.lat &&
northEast.lat > center.lat &&
northEast.lng > center.lng && // <-- this condition reversed
southWest.lng < center.lng; // <-- this condition reversed
Cause both latitude and longtitude in the southWest edge are greater than coordinates in the center. And both coordinates in northEast should be lower.
Upvotes: 2