Google Maps API v3, jQuery UI Tabs, map not resizing

后端 未结 5 1802
闹比i
闹比i 2020-12-10 09:34

I am using Google Maps API v3, being displayed on a jQuery UI Tab. I have been struggling with triggering my google map to resize correctly when the tab displaying the map

5条回答
  •  长情又很酷
    2020-12-10 10:30

    I know that this topic is ancient but think that this may be useful to someone.

    To avoid rendering problem with jQuery UI Tabs and Google Maps on some of that tabs, you can do following:

    //global variables
    var gMapsCentralLocation;   //some initial map center location
    var mapCenter;              //we will use this to overide your initialy map center so we can "remember" initial viewport when we go back and forth trought tabs
    var mapCenterFlag = false;  //indicate if we need to use new google maps viewpoint center, or use initial.
    var map;                    //google map
    
    $(document).ready(function () {
        $('#YourTabs').tabs({
            show: function (event, ui) {
                switch (ui.tab.hash) {
                    case "#GoogleMapsTab":
                        {
                            preRenderGoogleMaps();
                        }
                        break;
                    default:
                        {
                            //to save previous map center when user select some other tab
                            if (map) {
                                mapCenter = map.getCenter();
                            }
                        }
                        break;
                }
            }
        });
        drawRegionOnMap();
    });
    
    function preRenderGoogleMaps(){
        //fix rendering issues
        google.maps.event.trigger(map, 'resize');
    
        if (!mapCenterFlag) {
            map.setCenter(gMapsCentralLocation);
            mapCenterFlag = true;
        } else {
            map.setCenter(mapCenter);
        }
    }
    
    function drawRegionOnMap() {
        map = null;    
    
        var gMapsOptions = {
            zoom: 8,
            center: gMapsCentralLocation,
            //POSSIBLE MAP TYPES (ROADMAP, SATELLITE, HYBRID, TERRAIN)
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
    
        map = new google.maps.Map(document.getElementById("map_canvas"), gMapsOptions);
    }
    

提交回复
热议问题