Google Maps JavaScript API - fitbounds together with setCenter

后端 未结 2 758
Happy的楠姐
Happy的楠姐 2021-01-14 06:55

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.

相关标签:
2条回答
  • 2021-01-14 07:37

    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.

    0 讨论(0)
  • 2021-01-14 07:47

    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);
    
    0 讨论(0)
提交回复
热议问题