3

I'm currently working on a responsive website with a page-wide div-box containing a Google Map. As the display width (and height) varies, I'd need to set a different zoom level at width 320 as I do at 1200+. Resizing is not the issue nor is centering.

What I want to achieve is the zoom level to adjust as the viewport changes, either by setting different zoom levels corresponding to certain screen resolutions or something from min to max zoom.

I think this post on Stackoverflow pretty much is about the same problem, but without solution. Any ideas greatly appreciated!

Community
  • 1
  • 1
gfaw
  • 715
  • 1
  • 7
  • 10
  • 1
    You need to define what you want to be constant (or at least as constant as possible). Do you have a bounds on the map that you always want visible? If so define it as a google.maps.LatLngBounds and use the google.maps.Map.fitBounds method. – geocodezip Nov 04 '13 at 18:20

2 Answers2

0

You need the bounding box,i.e. corners of the window. Then you can use the mercator projection to compute the x and y ratio:Convert lat/lon to pixel coordinate?. Then you can multiply the ratio with the zoom levels and check min and max values.

Community
  • 1
  • 1
Micromega
  • 12,486
  • 7
  • 35
  • 72
0

Tricky problem indeed. It's best to set a timer in the resize event handler as that event can fire a lot.

var zoomLevelSizes = [
  {triggerWidth: 10000, zoomLevel: 9 },
  {triggerWidth: 720, zoomLevel: 8 },
  {triggerWidth: 320, zoomLevel: 7 }
];

var resizeTimeout = -1;
function handleResizeEvent() {
  resizeTimeout = -1;
  var width = window.innerWidth;
  for(var i = zoomLevelSizes.length - 1; i >= 0; i--) {
    if(width < zoomLevelSizes[i].triggerWidth) {
      if(map.getZoom() > zoomLevelSizes[i].zoomLevel) {
        map.setZoom(zoomLevelSizes[i].zoomLevel);
        console.log('changed to zoom level ' + zoomLevelSizes[i].zoomLevel);
        break;
      }
    }
  }
}
handleResizeEvent()

//Can't do anything resource intensive here as this can get triggered a lot
google.maps.event.addDomListener(window, 'resize', function() {
  if(resizeTimeout !== -1) {
    clearTimeout(resizeTimeout);
  }
  resizeTimeout = setTimeout(handleResizeEvent, 500);
});

JSFiddle example

Chad Killingsworth
  • 14,360
  • 2
  • 34
  • 57