Skip to content

Instantly share code, notes, and snippets.

@sharapeco
Created September 5, 2018 08:33
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 sharapeco/718c05f427fb5eea1d6776f8f62f733f to your computer and use it in GitHub Desktop.
Save sharapeco/718c05f427fb5eea1d6776f8f62f733f to your computer and use it in GitHub Desktop.
Google Maps API fitBoundsPerfectly
// 2014-12-16
google.maps.Map.prototype.fitBoundsPerfectly = function fitBoundsPerfectly(aBounds) {
var mapBounds, mapSW, mapNE, mapDLat, mapDLng, aSW, aNE, dLat, dLng, ratio, dZoom;
mapBounds = this.getBounds();
mapSW = mapBounds.getSouthWest();
mapNE = mapBounds.getNorthEast();
mapDLat = mapNE.lat() - mapSW.lat();
mapDLng = mapNE.lng() - mapSW.lng();
aSW = aBounds.getSouthWest();
aNE = aBounds.getNorthEast();
dLat = aNE.lat() - aSW.lat();
dLng = aNE.lng() - aSW.lng();
ratio = Math.max(dLat / mapDLat, dLng / mapDLng);
dZoom = -Math.ceil(Math.log(ratio) / Math.log(2));
if (dZoom) {
this.setZoom(this.getZoom() + dZoom);
}
this.panTo(aBounds.getCenter());
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment