首页 > 解决方案 > FitBounds 在 googlemaps javascript 中不起作用

问题描述

我有一张地图和一个标记列表,每个标记在 LatLng 对象中都有一个位置。该位置有效,因为我可以看到地图上的标记。但是我想使地图适合标记,所以我使用如下正确的语法。然而,地图永远不会在这两个位置缩放和居中。相反,它加载在初始中心,我在 initMap 中配置的缩放。请问有人能确定问题吗???

var bounds = new google.maps.LatLngBounds();
var location = new google.maps.LatLng(25.36234, 15.3623);
var location2 = new google.maps.LatLng(38.2352, 12.36435);
bounds.extend(location2);
bounds.extend(location);
window.parent.map.fitBounds(bounds);
window.parent.map.setCenter(bounds.getCenter());

标签: javascriptgoogle-mapsgoogle-maps-api-3mapsfitbounds

解决方案


window.parent.map解决您的问题似乎有点奇怪。
这应该可以解决您的问题。

var map;

  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 6,
    center: new google.maps.LatLng(39.5473234, 35.3796685),
    mapTypeId: 'roadmap'
  });


  var bounds = new google.maps.LatLngBounds();
  var location = new google.maps.LatLng(25.36234, 15.3623);
  var location2 = new google.maps.LatLng(38.2352, 12.36435);
  bounds.extend(location2);
  bounds.extend(location);
  map.fitBounds(bounds);
  map.setCenter(bounds.getCenter());

推荐阅读