Google Maps JavaScript API - fitbounds together with setCenter

亡梦爱人 提交于 2019-12-01 09:10:48

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.

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!