谷歌地图 JavaScript API - fitbounds 与 setCenter 结合使用

3
我一直在寻找解决这个问题的方法,但似乎找不到解决方案。最接近的是这个线程,但它没有起作用。
我想要做的是基于一组标记运行fitbounds,这很好。但我也想根据用户位置(plunk中的跳动标记)使地图居中,并仍然保持所有标记在地图视图内。 如果我在fitBounds后设置setCenter,那么一些标记就会在地图视图之外。 有没有巧妙的方法将这两个函数结合起来? 这里是说明该问题的plunk
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);
}

谢谢!

3个回答

4

简单解决方案:将您的“用户标记”添加到边界框中,执行fitBounds,然后将结果缩小1并居中到该标记。

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

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

演示示例

更复杂的方案: 以“用户标记”为中心,检查标记边界是否完全包含在地图当前边界内(map.getBounds().contains(markerBounds)),如果不是,则将缩放级别减少1。


谢谢@goecodezip!我会尝试提供的两种方法。 我认为更复杂的那个在我的情况下更合适。 我不知道你可以做.contains(bounds),只是.contains.(marker)。看起来很有前途! - Jan Banan
2
你确定可以将一个bounds类传递给.contains函数吗?这会为我抛出异常。查看API文档,它说bounds.contains()接受一个latlng,而不是bounds类。https://developers.google.com/maps/documentation/javascript/reference#LatLngBounds - Jan Banan

0

上面的答案对我没用。这是我做的:

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
如果您拥有边界和中心,则可以通过检查当前地图范围是否包含标记边界的中心和角落,并在不包含时增加缩放来完成此操作:
function fitBoundsAroundCenter( center, bounds, map ) {
    map.fitBounds( bounds );
    map.setCenter( center );
    let zoomPoints = []
    zoomPoints.push( center );
    zoomPoints.push( bounds.getNorthEast() );
    zoomPoints.push( bounds.getSouthWest() );
    
    let allInView = false;
    while ( false === allInView ) {
        map.setZoom( map.getZoom() - 1 );
        allInView = zoomPoints.every( point => {
            if ( map.getBounds().contains( point ) ) {
                return true;
            }
            return false;
        });
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接