Last active
November 7, 2017 14:21
-
-
Save costasovo/0bcb8302f4ac7604b24e7d79e8dc4e97 to your computer and use it in GitHub Desktop.
Computing bounds from latitude and longitude and size [meters]
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
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