Skip to content

Instantly share code, notes, and snippets.

@pianosnake
Last active July 17, 2024 14:19
Show Gist options
  • Save pianosnake/b4a45ef6bdf2ffb2e1b44bbcca107298 to your computer and use it in GitHub Desktop.
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.
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
@emyb
Copy link

emyb commented Dec 7, 2023

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)
);

@emyb
Copy link

emyb commented Dec 7, 2023

This was helpful for me

@Milvintsiss
Copy link

Works like a charm ! Thanks !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment