fitbounds覆盖所有可用的标记google map api

时间:2018-04-09 07:30:53

标签: javascript google-maps

我已使用map.fitbounds缩放地图并将地图居中以显示可用的标记。这是我的代码,

 marker = new google.maps.Marker(
 {
  map:map,
  draggable:true,
  animation: google.maps.Animation.DROP,
  icon: icon
 });

 marker2 = new google.maps.Marker(
 {
 map:map,
 draggable:true,
 animation: google.maps.Animation.DROP,
 icon:icon
 });

 var bounds = new google.maps.LatLngBounds();
 var markers = [marker, marker2];
 for (i = 0; i < markers.length; i++) {
 position = new google.maps.LatLng(markers[i][0], markers[i][1]);

 bounds.extend(position)
 }
map.fitBounds(bounds);

但上面的代码不起作用。我怎么解决呢?

1 个答案:

答案 0 :(得分:0)

试试这个。我认为你在bounds.extend()中使用了错误的变量......这段代码对我有用

var createMarker = function (info){
        var marker = new google.maps.Marker({
            position: new google.maps.LatLng(info.latitude, info.longitude),
            map: $scope.map,
            animation: google.maps.Animation.DROP,


        });
        loc = new google.maps.LatLng(info.latitude, info.longitude);
        bounds.extend(loc);

    }  
    for (i = 0; i < markers.length; i++){
        createMarker(markers[i]);
    }
    map.fitBounds(bounds);