如何设置地图缩放以显示标签页Bootstrap中的所有标记?

时间:2017-03-08 20:09:43

标签: javascript jquery model-view-controller

我使用此代码在标签页中执行谷歌地图,但不显示标签中的所有标记。 如何设置缩放谷歌地图以显示标签页中的所有标记。   " map.fitBounds(latlngbounds);"没有在TabPage中工作。 我怎么能这样做?

<!DOCTYPE html>
<html>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<body>

<h1>My First Google Map</h1>
<ul class="nav nav-tabs">
  <li class="active"><a data-toggle="tab" href="#home">Home</a></li>
  <li><a data-toggle="tab" href="#menu1">Menu 1</a></li>
  <li><a data-toggle="tab" href="#menu2">Menu 2</a></li>
</ul>

<div class="tab-content">
  <div id="home" class="tab-pane fade in active">
    <h3>HOME</h3>
    <p>Some content.</p>
  </div>
  <div id="menu1" class="tab-pane fade">
    <h3>Menu 1</h3>

<div id="map" style="width:100%;height:400px;"></div>
  </div>
  <div id="menu2" class="tab-pane fade">
    <h3>Menu 2</h3>
    <p>Some content in menu 2.</p>
  </div>
</div>

<script>
function myMap() {
  var mapCanvas = document.getElementById("map");
  var mapOptions = {
    center: new google.maps.LatLng(51.5, -0.2), zoom: 10
  };
  var map = new google.maps.Map(mapCanvas, mapOptions);
$(function () {
      $('a[href="#menu1"]').on('shown.bs.tab', function (e) {
          var lastCenter = map.getCenter();
          google.maps.event.trigger(map, 'resize');
          map.setCenter(lastCenter);

      });
  });
var locations=[];
locations.push({neme:"Country1",latlng:new google.maps.LatLng(46.71285452819798, 20.36901795864105)});  
locations.push({neme:"Country2",latlng:new google.maps.LatLng(51.71285452819798, 10.36901795864105)});  
locations.push({neme:"Country3",latlng:new google.maps.LatLng(62.71285452819798, 30.36901795864105)});  

var latlngbounds = new google.maps.LatLngBounds();

for(var i=0;i<locations.length;i++)
{

   var marker = new google.maps.Marker({
                position: locations[i].latlng,
                map: map,
                title:locations[i].name
               //zoom:8
            });
latlngbounds.extend(marker.position);
}

//Get the boundaries of the Map.
        var bounds = new google.maps.LatLngBounds();

        //Center map and adjust Zoom based on the position of all markers.
        map.fitBounds(latlngbounds);
}
</script>

<script src="https://maps.googleapis.com/maps/api/js?your-key-Api&callback=myMap"></script>

</body>
</html>

1 个答案:

答案 0 :(得分:0)

这是因为你的地图还没准备好。你需要使用地图回调。 jQuery.ready没有捕获map.ready。

<script>
  var map;
  function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
      center: {lat: -34.397, lng: 150.644},
      zoom: 8
    });
  }
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"
async defer></script>

所有与地图相关的功能都应该在initMap函数内部,或者应该在其中调用。