how to deal with google map inside of a hidden div

2019-01-03 12:34发布

i have a page and a google map is inside a hidden div at first. I then show the div after i click a link but only the top left of the map shows up.

i tried having this code run after the click:

    map0.onResize();

or:

  google.maps.event.trigger(map0, 'resize')

any ideas. here is an image of what i see after showing the div with the hidden map in it.alt text

23条回答
Explosion°爆炸
2楼-- · 2019-01-03 12:51

My solution was:

CSS:

.map {
   height: 400px;
   border: #ccc solid 1px;
}

jQuery:

$('.map').width(555); // width of map canvas
查看更多
太酷不给撩
3楼-- · 2019-01-03 12:52

I had a Google map inside a Bootstrap tab, which wasn't displaying correctly. This was my fix.

// Previously stored my map object(s) in googleMaps array

$('a[href="#profileTab"]').on('shown', function() {   // When tab is displayed...
    var map = googleMaps[0],
        center = map.getCenter();
    google.maps.event.trigger(map, 'resize');         // fixes map display
    map.setCenter(center);                            // centers map correctly
});
查看更多
别忘想泡老子
4楼-- · 2019-01-03 12:54

I was having the same problem and discovered that when show the div, call google.maps.event.trigger(map, 'resize'); and it appears to resolve the issue for me.

查看更多
干净又极端
5楼-- · 2019-01-03 12:58
google.maps.event.trigger($("#div_ID")[0], 'resize');

If you don't have variable map available, it should be the first element (unless you did something stupid) in the div that contains GMAP.

查看更多
smile是对你的礼貌
6楼-- · 2019-01-03 12:59

Just as John Doppelmann and HoffZ have indicated, put all code together just as follows in your div showing function or onclick event:

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

It worked perfectly for me

查看更多
一纸荒年 Trace。
7楼-- · 2019-01-03 12:59

function init_map() {
  var myOptions = {
    zoom: 16,
    center: new google.maps.LatLng(0.0, 0.0),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById('gmap_canvas'), myOptions);
  marker = new google.maps.Marker({
    map: map,
    position: new google.maps.LatLng(0.0, 0.0)
  });
  infowindow = new google.maps.InfoWindow({
    content: 'content'
  });
  google.maps.event.addListener(marker, 'click', function() {
    infowindow.open(map, marker);
  });
  infowindow.open(map, marker);
}
google.maps.event.addDomListener(window, 'load', init_map);

jQuery(window).resize(function() {
  init_map();
});
jQuery('.open-map').on('click', function() {
  init_map();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src='https://maps.googleapis.com/maps/api/js?v=3.exp'></script>

<button type="button" class="open-map"></button>
<div style='overflow:hidden;height:250px;width:100%;'>
  <div id='gmap_canvas' style='height:250px;width:100%;'></div>
</div>

查看更多
登录 后发表回答