Google Maps JavaScript API - fitbounds together with setCenter

偶尔善良 提交于 2019-12-01 06:04:57

问题


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 trying to do is to run fitbounds based on a set of markers which works fine. But i would also like to center the map based on the users location (the bouncing marker in the plunk) and still keep all markers within the map view. If i try to setCenter after fitBounds, some markers are outside of the map view. Is there some nifty way of combining these two functions? Here's the plunk illustrating the issue.

function initialize() {
  var userCenter = new google.maps.LatLng(51.508742, -0.120850);

  var userCenterMarker = new google.maps.Marker({
  position: userCenter
});

 userCenterMarker.setAnimation(google.maps.Animation.BOUNCE);

var mapProp = {
  center: userCenter,
  zoom: 12,
  mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("googleMap"),   mapProp);

var bounds = new google.maps.LatLngBounds();
var markers = getMarkers();

$(markers).each(function() {
  bounds.extend(this.position);
  this.setMap(map);
});

userCenterMarker.setMap(map);

map.fitBounds(bounds);

setTimeout(function() {
  map.setCenter(userCenter);
}, 1500);
}

Thanks!


回答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.




回答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);


来源:https://stackoverflow.com/questions/28502932/google-maps-javascript-api-fitbounds-together-with-setcenter

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