在调整地图容器大小后,如何居中和缩放Google地图?

时间:2015-08-31 09:49:31

标签: javascript google-maps google-maps-api-3

我有一张带有许多标记的地图。

enter image description here

调整地图大小后,它看起来像这样:

enter image description here

我想要这个:

enter image description here

如何在调整大小后放大并将地图放在标记上?

我有以下代码;

var map;

var GoogleMaps = {
  setMarkers: function(stores){
    map = new google.maps.Map(document.getElementById('map-canvas'));

    $.each(stores, function (key, store) {
      /* (..) */
      bounds.extend(latLng);
    });

    map.fitBounds(bounds);

    // This part is never triggered
    google.maps.event.addDomListener(window, 'resize', function() {
      var center = map.getCenter();
      google.maps.event.trigger(map, "resize");
      map.setCenter(center);    
    });
  }
}

HTML
当我单击调整大小图标时,我将css类添加到map-canvas

<div class="map-container alt-row row-spacer clearfix">
  <section class="column12">
    <div id="map-canvas" class=""></div>
  </section>
</div>

我已经查看了类似的问题(herehere),但它们并没有解决我的问题。

有谁知道我怎么能做到这一点?你可以look at my JSFiddle here

2 个答案:

答案 0 :(得分:0)

重新设置地图以适应边界应该在map div调整大小时起作用:

google.maps.event.addDomListener(document.getElementById('map-canvas'), 'resize', function() {
  google.maps.event.trigger(map, "resize");
  map.fitBounds(bounds);
});

答案 1 :(得分:0)

您可以为此目的尝试idle而不是resize事件。

示例

&#13;
&#13;
var map;

var GoogleMaps = {
    setMarkers: function (stores) {
        map = new google.maps.Map(document.getElementById('map-canvas'));

        var bounds = new google.maps.LatLngBounds();
        $.each(stores, function (key, store) {

            var storePos = new google.maps.LatLng(store[1], store[2]);

            var marker = new google.maps.Marker({
                position: storePos,
                title: store[0],
                map: map
            });


            bounds.extend(storePos);
        });

        map.fitBounds(bounds);


        /*google.maps.event.addDomListener(map, 'resize', function () {
            var center = map.getCenter();
            google.maps.event.trigger(map, "resize");
            map.setCenter(center);
        });*/

        google.maps.event.addListener(map, 'idle', function (event) {
            var center = map.getCenter();
            map.setCenter(center);
            document.getElementById('result').innerHTML += 'Adjusted..';
        });
    }
}


google.maps.event.addDomListener(window, 'load', function () {
    var stores = [
        ['0183 Oslo, Norja', 59.918816, 10.751814],
        ['1154 Oslo, Norja', 59.873011, 10.814299],
        ['0264 Oslo, Norja', 59.916751, 10.705809]
    ];
    GoogleMaps.setMarkers(stores);
});
&#13;
html, body, #map-canvas {
     height: 100%;
     margin: 0px;
     padding: 0px;
 }
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<div id="map-canvas"></div>
<div id='result'/>
&#13;
&#13;
&#13;