我正在尝试在响应式网站的地图中显示某个区域。我希望它在加载时显示相同的区域,无论窗口大小如何,通过放大和缩小。经过一番研究,我了解到我需要使用 Google Maps JS API 的 fitBounds 函数,但无法使其正常工作。到目前为止,这是我的代码:
<div id="map"></div><!--css rules to make it a 16/9 responsive box-->
<script src="https://maps.googleapis.com/maps/api/js?key=mykey" type="text/javascript"></script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(x, y), //any coordinates I put here don't matter, as I need the map to adjust using bounds, right?
zoom: 11
};
var bounds = google.maps.LatLngBounds(
new google.maps.LatLng(x, y), //SW coordinates here
new google.maps.LatLng(x, y) //NE coordinates here
);
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addDomListener(window, "resize", function() {
var bounds = map.getBounds();
google.maps.event.trigger(map, "resize");
map.fitBounds(bounds);
});
</script>
似乎地图只是在选项中显示了中心位置,而忽略了 fitBounds 调用。我错过了什么/做错了什么?