我在 map 上有 2 个标记。当某些事件发生时,我想让这两个标记在 map 上可见。但是当我在 map 上添加 restriction
选项时 fitBounds
不显示标记。当我删除 restriction
选项时,它似乎可以正常工作。
下面是示例代码:
var map, markers;
var locations = [{
lat: 50.8503396,
lng: 4.351710300000036
},
{
lat: 49.9570366,
lng: 36.3431478
},
];
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 1,
center: {
lat: -28.024,
lng: 140.887
},
restriction: {
strictBounds: true,
latLngBounds: {
north: 85,
south: -85,
west: -180,
east: 180
},
},
});
markers = locations.map(function(location, i) {
return new google.maps.Marker({
position: location
});
});
markers.forEach(function(marker) {
marker.setMap(map);
});
}
setTimeout(function() {
var bounds = new google.maps.LatLngBounds();
markers.forEach(function(marker) {
bounds.extend(marker.position);
});
map.fitBounds(bounds);
}, 5000);
#map {
height: 400px;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>
最佳答案
虽然 google.maps.api 的这个错误仍然存在,但您可以将 map 中心设置为边界中心作为解决方法。
map.fitBounds(bounds);
map.setCenter(bounds.getCenter());
关于javascript - 本地图设置了 'restriction' 选项时,map.fitBounds 的工作很奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54712021/