Skip to content Skip to sidebar Skip to footer

Google Maps JavaScript API - Fitbounds Together With SetCenter

I've been looking around for a solution to this problem, but i can't seem to find somthing that solves this. The closest i get is this thread. But this doesn't work. What i'm tryin

Solution 1:

Simple solution: Add your "user marker" to the bounds, do fitBounds, then decrement the resulting zoom by 1 and center on that marker.

  bounds.extend(userCenterMarker.getPosition());
  map.fitBounds(bounds);

  google.maps.event.addListenerOnce(map,'bounds_changed', function() {
        map.setZoom(map.getZoom()-1);
  });

working fiddle

More complex solution: Center on the "user marker", check to see if the marker bounds is completely included in the map's current bounds (map.getBounds().contains(markerBounds)), if not, decrement the zoom level by 1.


Solution 2:

The above answer didn't work for me. Here's what did:

contained = true;
map.fitBounds(bounds);
map.setCenter(center);
newbounds = map.getBounds();
for (i = 0; i < l; i ++) {
  if (!newbounds.contains(markers[i].getPosition())) {
    contained = false;
  }
}
if (!contained) map.setZoom(map.getZoom() - 1);

Post a Comment for "Google Maps JavaScript API - Fitbounds Together With SetCenter"