I’m interested in determining if a lat/lng location is within the bounds and looking for recommendations on a algorithm. (javascript or php)
Here is what I have so far:
JavaScript
x
7
1
var lat = somelat;
2
var lng = somelng;
3
4
if (bounds.southWest.lat < lat && lat < bounds.northEast.lat && bounds.southWest.lng < lng && lng < bounds.northEast.lng) {
5
'lat and lng in bounds
6
}
7
will this work? thanks
Advertisement
Answer
The simple comparison in your post will work for coordinates in the US. However, if you want a solution that’s safe for checking across the International Date Line (where longitude is ±180°):
JavaScript
1
15
15
1
function inBounds(point, bounds) {
2
var eastBound = point.long < bounds.NE.long;
3
var westBound = point.long > bounds.SW.long;
4
var inLong;
5
6
if (bounds.NE.long < bounds.SW.long) {
7
inLong = eastBound || westBound;
8
} else {
9
inLong = eastBound && westBound;
10
}
11
12
var inLat = point.lat > bounds.SW.lat && point.lat < bounds.NE.lat;
13
return inLat && inLong;
14
}
15