javascript - 本地图设置了 'restriction' 选项时,map.fitBounds 的工作很奇怪

标签 javascript google-maps google-maps-api-3

我在 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>

https://jsfiddle.net/fedman/6eoty0vm/

最佳答案

虽然 google.maps.api 的这个错误仍然存​​在,但您可以将 map 中心设置为边界中心作为解决方法。

map.fitBounds(bounds);
map.setCenter(bounds.getCenter());

关于javascript - 本地图设置了 'restriction' 选项时,map.fitBounds 的工作很奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54712021/

相关文章:

javascript - 无法在 Google map 上加载 KML 图层

javascript - 按类别选择标记并适应可见标记

javascript - JavaScript中的 "==+!"是什么?

javascript - 获取道路的几何形状(线条/绘图)

javascript - if else 条件在 setInterval 的下一次传递后发生

angularjs - Google map 第二次无法加载 - AngularJS

android - getLastKnownLocation() 始终返回相同的位置,即使在移动设备后也是如此

google-maps - Google Places API 返回奇怪的结果

javascript - 无法在 mongoose 中存储 json 对象

Javascript/jquery : Remove parent of class and keep it's child