廉价的答案是总是在 fitBounds() 之后缩小一级。但我们可以做得更好。
我喜欢写小技巧。在这里,我假设标记的大小永远不会大于 36x57。我测试了一段时间后发现fitBounds() 在边缘和最近的标记之间留下了大约 42 px 的边距(可能不在手机上),而且我还假设您没有重新定位标记,也就是说,它会始终显示在给定坐标位置的上方。如果图标跑到另一边,则需要进行调整。
我的 hack 利用了一个测量 LatLng 像素位置的函数(使用容器版本,我在这里读到 div 版本在边界变化时不可靠)。
由于我们知道图标的高度以及最上面的标记在哪里,如果确定地图不在屏幕上,我们可以将地图向南平移一点。如果下面没有足够的边距,唯一的选择是缩小。我唯一担心的是它会很生涩,因为它需要两个事件:fitBounds 和自定义平移/缩放。那么唯一的答案就是重写一个自定义的fitBounds。当我手动测试时,事件运行顺利。
http://jsfiddle.net/sZJjY/
点击添加猫图标,右键触发调整大小/平移。
示例:放置 3-4 只小猫,单击鼠标右键,然后故意放置另一个超出顶部的小猫,再次单击鼠标右键。
function fitIcons() {
var left = 180.0;
var right = -180.0;
var top = -90.0;
var bottom = 90.0;
for (var i = 0; i < markers.length; i++) {
curlat = markers[i].getPosition().lat();
curlng = markers[i].getPosition().lng();
if(curlat > top) { top = curlat; }
if(curlat < bottom) { bottom = curlat; }
if(curlng > right) { right = curlng; }
if(curlng < left) { left = curlng; }
}
var overlay = new google.maps.OverlayView();
overlay.draw = function() {};
overlay.setMap(map);
map.fitBounds(new google.maps.LatLngBounds(
new google.maps.LatLng(bottom, left),
new google.maps.LatLng(top, right)));
topPixels = overlay.getProjection().fromLatLngToContainerPixel(
new google.maps.LatLng(top, right));
bottomPixels = overlay.getProjection().fromLatLngToContainerPixel(
new google.maps.LatLng(bottom, left));
topGap = topPixels.y;
bottomGap = $("#map_canvas").height() - bottomPixels.y;
if(topGap < iconHeight) {
if(bottomGap > iconHeight) {
map.panBy(0, topGap);
}
else {
map.setZoom(map.getZoom() - 1);
}
}
}