如何在包含display:none的选项卡或div中显示Google Maps Directions [英] How to show Google Maps Directions in tabs or div that has display:none

查看:127
本文介绍了如何在包含display:none的选项卡或div中显示Google Maps Directions的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我将Google地图(v3)与方向加载到对用户隐藏的div中时,结果地图不会正确放大和居中。我试着发射一个 resize 事件,但那只能部分解决问题。

When I'm loading a Google Map (v3) with Directions into a div that is hidden from the user, the resulting map is not zoomed and centered correctly. I tried firing a resize event but that did only partially solve the problem.

通常当用方向加载地图时,API会自动查找最佳视图(即缩放级别和中心)以显示整个旅程。任何想法我做错了什么?

Usually when loading a map with directions, the API automatically finds the optimal view (ie. zoom level and center) as to show the entire journey. Any ideas what I'm doing wrong?

请参阅 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:

And the javascript:

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


推荐答案

修改ready函数,如下所示:

Modify the ready-function as follows:

$(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");
        });
      });

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

It will , when a route is available inside the map, set the bounds of the map to the bounds of the route.

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

这篇关于如何在包含display:none的选项卡或div中显示Google Maps Directions的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆