Last active
December 29, 2015 14:19
-
-
Save blackjk3/7683346 to your computer and use it in GitHub Desktop.
Calculating a bounding box based on a single geo point.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var GeoUtils = { | |
MIN_LAT: -90 * Math.PI/180, // -PI/2 | |
MAX_LAT: 90 * Math.PI/180, // PI/2 | |
MIN_LON: -180 * Math.PI/180, // -PI | |
MAX_LON: 180 * Math.PI/180, // PI | |
computeBoundingCoordinates: function(coords, distance, radius) { | |
radius = 6371.01; // Size of the earth in kilometers | |
if (!distance || !radius) { | |
return; | |
} | |
var radDist = distance / radius; | |
coords.radLat *= Math.PI/180; | |
coords.radLon *= Math.PI/180; | |
var minLat = coords.radLat - radDist; | |
var maxLat = coords.radLat + radDist; | |
var minLon, maxLon, deltaLon; | |
if (minLat > GeoUtils.MIN_LAT && maxLat < GeoUtils.MAX_LAT) { | |
deltaLon = Math.asin( Math.sin(radDist) / Math.cos(coords.radLat) ); | |
minLon = coords.radLon - deltaLon; | |
if (minLon < GeoUtils.MIN_LON) { | |
minLon += 2 * Math.PI; | |
} | |
maxLon = coords.radLon + deltaLon; | |
if (maxLon > GeoUtils.MAX_LON) { | |
maxLon -= 2 * Math.PI; | |
} | |
} else { | |
// a pole is within the distance | |
minLat = Math.max(minLat, GeoUtils.MIN_LAT); | |
maxLat = Math.min(maxLat, GeoUtils.MAX_LAT); | |
minLon = GeoUtils.MIN_LON; | |
maxLon = GeoUtils.MAX_LON; | |
} | |
return { | |
minLat: GeoUtils.toDegrees(minLat), | |
minLon: GeoUtils.toDegrees(minLon), | |
maxLat: GeoUtils.toDegrees(maxLat), | |
maxLon: GeoUtils.toDegrees(maxLon) | |
}; | |
}, | |
toDegrees: function(val) { | |
return val * 180 / Math.PI; | |
}, | |
toRadians: function(val) { | |
return val *= Math.PI/180; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment