Google Maps JavaScript API - fitbound与setCenter一起使用 [英] Google Maps JavaScript API - fitbounds together with setCenter

查看:107
本文介绍了Google Maps JavaScript API - fitbound与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.

我想要做的是根据一组标记运行fitbounds,它可以正常工作。但我还想根据用户位置(跳动中的弹跳标记)将地图居中,并将所有标记保留在地图视图中。
如果我尝试在fitBounds之后设置中心,则某些标记位于地图视图之外。
有没有把这两种功能结合起来的巧妙方式?
这是解释问题的大块头

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!

推荐答案

简单的解决方案:将你的用户标记添加到界限,做fitBounds,然后将结果放大缩小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);
  });

工作小提琴

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

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.

这篇关于Google Maps JavaScript API - fitbound与setCenter一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆