1

当我将带有方向的 Google 地图 (v3) 加载到对用户隐藏的 div 中时,生成的地图不会正确缩放和居中。我尝试触发一个resize事件,但这只是部分解决了问题。

通常在加载带有路线的地图时,API 会自动找到最佳视图(即缩放级别和中心)以显示整个旅程。任何想法我做错了什么?

请参阅JsFiddle

<button id="show">Show</button>
<div id="a">
   <div id="map_wrapper" style="display:none">
      <div id="map_canvas" style="height: 354px; width:713px;"></div>
   </div>
  <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=initialize"></script>
  <script>
  var directionsService,
      directionsDisplay,
      map;

    function initialize() {

      directionsService = new google.maps.DirectionsService();
      directionsDisplay = new google.maps.DirectionsRenderer(); 
      var mapOptions = { mapTypeId: google.maps.MapTypeId.ROADMAP, disableDefaultUI: true }
      map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
      directionsDisplay.setMap(map);

      var start = 'New York, NY';
      var end = 'Chicago, IL';
      var request = { origin: start, destination: end, travelMode: google.maps.DirectionsTravelMode.DRIVING };
      directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);
        }
      });
    }
  </script>
</div>

和javascript:

$(document).ready(function(e) {
    $('#show').on('click', function() {
        $('#map_wrapper').show();
        google.maps.event.trigger(map, "resize");
    });
});
4

3 回答 3

0

您可以在单击按钮后初始化地图:删除回调,单击initialize()按钮时全部调用。http://jsfiddle.net/mB6AZ/2/

于 2013-01-10T17:24:02.390 回答
0

保存 DirectionsRoute LatLngBounds 的副本,然后在调整大小后使地图适应这些边界。

工作演示

var bounds;

directionsService.route(request, function (response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
      bounds = response.routes[0].bounds;
    }
});

$(document).ready(function (e) {
  $('#show').on('click', function () {
    $('#map_wrapper').show(0, function () {
      // this will fire once the map resize completes
      google.maps.event.addListenerOnce(map, 'idle', function () {
        this.fitBounds(bounds);
      });
      google.maps.event.trigger(map, "resize");
    });
  });
});
于 2013-01-10T18:03:21.410 回答
0

修改ready-function如下:

$(document).ready(function(e) {
        $('#show').on('click', function() {
            $('#map_wrapper').show();
            google.maps.event.addListenerOnce(map, "resize",function(){
              try{this.fitBounds(directionsDisplay.getDirections().routes[0].bounds)
              }catch(e){}
            });
            google.maps.event.trigger(map, "resize");
        });
      });

当地图内有可用路线时,它将地图的边界设置为路线的边界。

演示:http: //jsfiddle.net/doktormolle/c2pC3/

于 2013-01-11T01:04:01.303 回答