Skip to content

Instantly share code, notes, and snippets.

@prog
Created May 3, 2016 12:59
Show Gist options
  • Save prog/e707b0cbd94a854433018b3d7610bc7e to your computer and use it in GitHub Desktop.
Save prog/e707b0cbd94a854433018b3d7610bc7e to your computer and use it in GitHub Desktop.
Max google maps zoom to fit specified bounds
function getZoom(bounds, width, height, maxZoom = 15) {
var WORLD_DIM = { height: 256, width: 256 };
function latRad(lat) {
var sin = Math.sin(lat * Math.PI / 180);
var radX2 = Math.log((1 + sin) / (1 - sin)) / 2;
return Math.max(Math.min(radX2, Math.PI), -Math.PI) / 2;
}
function zoom(mapPx, worldPx, fraction) {
return Math.floor(Math.log(mapPx / worldPx / fraction) / Math.LN2);
}
var ne = bounds.getNorthEast();
var sw = bounds.getSouthWest();
var latFraction = (latRad(ne.lat()) - latRad(sw.lat())) / Math.PI;
var lngDiff = ne.lng() - sw.lng();
var lngFraction = ((lngDiff < 0) ? (lngDiff + 360) : lngDiff) / 360;
var latZoom = zoom(height, WORLD_DIM.height, latFraction);
var lngZoom = zoom(width, WORLD_DIM.width, lngFraction);
return Math.min(latZoom, lngZoom, maxZoom);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment