Skip to content

Instantly share code, notes, and snippets.

@ethul
Created October 29, 2014 15:46
Show Gist options
  • Save ethul/a17c43bb9fdfd7dd1c2e to your computer and use it in GitHub Desktop.
Save ethul/a17c43bb9fdfd7dd1c2e to your computer and use it in GitHub Desktop.
// From https://code.google.com/p/gmaps-api-issues/issues/detail?id=3117#c12
function googleMapsFitBoundsAndZoom(google, map, bounds) {
function myFitBounds(myMap, bounds) {
myMap.fitBounds(bounds);
var overlayHelper = new google.maps.OverlayView();
overlayHelper.draw = function () {
if (!this.ready) {
var zoom = getExtraZoom(this.getProjection(), bounds, myMap.getBounds());
if (zoom > 0) {
myMap.setZoom(myMap.getZoom() + zoom);
}
this.ready = true;
google.maps.event.trigger(this, 'ready');
}
};
overlayHelper.setMap(myMap);
}
// LatLngBounds b1, b2 -> zoom increment
function getExtraZoom(projection, expectedBounds, actualBounds) {
var expectedSize = getSizeInPixels(projection, expectedBounds),
actualSize = getSizeInPixels(projection, actualBounds);
if (Math.floor(expectedSize.x) == 0 || Math.floor(expectedSize.y) == 0) {
return 0;
}
var qx = actualSize.x / expectedSize.x;
var qy = actualSize.y / expectedSize.y;
var min = Math.min(qx, qy);
if (min < 1) {
return 0;
}
return Math.floor(Math.log(min) / Math.log(2) /* = log2(min) */);
}
// LatLngBounds bnds -> height and width as a Point
function getSizeInPixels(projection, bounds) {
var sw = projection.fromLatLngToContainerPixel(bounds.getSouthWest());
var ne = projection.fromLatLngToContainerPixel(bounds.getNorthEast());
return new google.maps.Point(Math.abs(sw.y - ne.y), Math.abs(sw.x - ne.x));
}
return myFitBounds(map, bounds);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment