Skip to content

Instantly share code, notes, and snippets.

@costasovo
Last active November 7, 2017 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save costasovo/0bcb8302f4ac7604b24e7d79e8dc4e97 to your computer and use it in GitHub Desktop.
Save costasovo/0bcb8302f4ac7604b24e7d79e8dc4e97 to your computer and use it in GitHub Desktop.
Computing bounds from latitude and longitude and size [meters]
export function createBoundsFromLocationAndSize(
location: Location,
width: number,
height: number
): Bounds {
const diagonal: number = Math.sqrt(width * width + height * height);
const alpha: number = toDegrees(Math.asin(height / diagonal));
const sw: Location = locationWithOffset(location, diagonal, 270 - alpha);
const ne: Location = locationWithOffset(location, diagonal, 90 - alpha);
return {
south: sw.lat,
west: sw.lng,
north: ne.lat,
east: ne.lng
} as Bounds;
}
function locationWithOffset(location: Location, distance: number, heading: number): Location {
heading = toRadians(heading);
const latRad: number = toRadians(location.lat);
const lngRad: number = toRadians(location.lng);
const dR: number = distance / EARTH_RADIUS; // radius of the Earth in meters
const finalLat: number = Math.asin(
Math.sin(latRad) * Math.cos(dR) + Math.cos(latRad) * Math.sin(dR) * Math.cos(heading)
);
const finalLng: number = lngRad + Math.atan2(
Math.sin(heading) * Math.sin(dR) * Math.cos(latRad), Math.cos(dR) - Math.sin(latRad) * Math.sin(finalLat)
);
return {
lat: toDegrees(finalLat),
lng: toDegrees(finalLng)
};
}
function toRadians(degrees: number): number {
return degrees * Math.PI / 180;
}
function toDegrees(radians: number): number {
return radians * 180 / Math.PI;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment