Google map's marker not center after resize on bootstrap tab

强颜欢笑 提交于 2019-12-03 21:51:14

In bootstrap 3.x.x, this script will help:

    var map;
    google.maps.visualRefresh = true;     // Enable the visual refresh
    function initialize() {
          // map initialization code 
    }

    google.maps.event.addDomListener(window, 'load', initialize);

    $(function () {
        $('a[href="#Location"]').on('shown.bs.tab', function(e) {
            lastCenter=map.getCenter();
            google.maps.event.trigger(map, 'resize');
            map.setCenter(lastCenter);

        });
    });

where a[href="#Location"] is the anchor selector of the tab.

I checked your page source and found that you're using setTimeout(initialise, 1000); Therefore it is bit slow to show map. Try replacing the below code.

$(document).ready(function() {
        $('a[href="#tab2"]').click(function(e) {
            initialise();
        });

Try this:

var map = null;

var center = null;

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

function initMap() 
{
    map = new google.maps.Map(document.getElementById("Your div id"), 
    {
       center: new google.maps.LatLng("mycenter"),
       zoom: 10,
       mapTypeId: google.maps.MapTypeId.ROADMAP,
    });

    center = bounds.getCenter();

    map.fitBounds(bounds);
}

I had the same problem with Google Maps and Bootstrap Tab plugin.

I used the 'shown' event to initialize google map in tab instead of the 'click' event.

$('a[href="#tab2"]').on('shown',function(e) {
    // Initialized once the google map
    // ...
    // ...

    // use this to redraw google map when current tab is shown.
    google.maps.event.trigger(document.getElementById('Your div id'), 'resize');
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!