Last active
January 20, 2025 20:18
-
-
Save pianosnake/b4a45ef6bdf2ffb2e1b44bbcca107298 to your computer and use it in GitHub Desktop.
Get a bounding box from latitude, longitude, zoom level and image size. Useful for getting the bounding box of a static map generated with only those variables.
This file contains hidden or 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
const EARTH_CIR_METERS = 40075016.686; | |
const degreesPerMeter = 360 / EARTH_CIR_METERS; | |
function toRadians(degrees) { | |
return degrees * Math.PI / 180; | |
}; | |
function latLngToBounds(lat, lng, zoom, width, height){ | |
const metersPerPixelEW = EARTH_CIR_METERS / Math.pow(2, zoom + 8); | |
const metersPerPixelNS = EARTH_CIR_METERS / Math.pow(2, zoom + 8) * Math.cos(toRadians(lat)); | |
const shiftMetersEW = width/2 * metersPerPixelEW; | |
const shiftMetersNS = height/2 * metersPerPixelNS; | |
const shiftDegreesEW = shiftMetersEW * degreesPerMeter; | |
const shiftDegreesNS = shiftMetersNS * degreesPerMeter; | |
// [[south, west], [north, east]] | |
return [[lat-shiftDegreesNS, lng-shiftDegreesEW], [lat+shiftDegreesNS, lng+shiftDegreesEW]]; | |
} | |
// Example | |
// get an image from http://staticmap.openstreetmap.de/staticmap.php?center=34.03827,-118.25667&zoom=11&size=1024x576&maptype=mapnik | |
// compute the bounds of the static image | |
// latLngToBounds(34.03827, -118.25667, 11, 1024, 576) //returns [-118.6082325, 33.8743984804183, -117.9051075, 34.202141519581694] | |
// overlay static image in leaflet with those bounds will put the image in the correct location on the map |
I have tried this out and unfortunately it does not work:
latLngToBounds(34.03827, -118.25667, 11, 1024, 576)
returns:
[[ 33.8743984804183, -118.6082325 ],[ 34.202141519581694, -117.9051075 ]]
Which is the exact opposite of what it should return.
One might be interested in this: https://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Lon..2Flat._to_bbox
You just have to put those in your new google.maps.LatLng() when making your new google.maps.LatLngBounds()
let theBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(33.8743984804183, -118.6082325),
new google.maps.LatLng(34.202141519581694, -117.9051075)
);
This was helpful for me
Works like a charm ! Thanks !
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Dude that was what I'm searching for, Thanks