Google maps responsive resize

后端 未结 2 522
清歌不尽
清歌不尽 2020-11-28 20:03

I\'m trying to get google maps responsive and resize while keeping its center when windows resizes. I read other stack questions in regards such as:

Responsive Googl

相关标签:
2条回答
  • 2020-11-28 20:38

    Move your map variable into a scope where the event listener can use it. You are creating the map inside your initialize() function and nothing else can use it when created that way.

    var map; //<-- This is now available to both event listeners and the initialize() function
    function initialize() {
      var mapOptions = {
       center: new google.maps.LatLng(40.5472,12.282715),
       zoom: 6,
       mapTypeId: google.maps.MapTypeId.ROADMAP
      };
      map = new google.maps.Map(document.getElementById("map-canvas"),
                mapOptions);
    }
    google.maps.event.addDomListener(window, 'load', initialize);
    google.maps.event.addDomListener(window, "resize", function() {
     var center = map.getCenter();
     google.maps.event.trigger(map, "resize");
     map.setCenter(center); 
    });
    
    0 讨论(0)
  • 2020-11-28 20:57

    After few years, I moved to leaflet map and I have fixed this issue completely, the following could be applied to google maps too:

        var headerHeight = $("#navMap").outerHeight();
        var footerHeight = $("footer").outerHeight();
        var windowHeight = window.innerHeight;
        var mapContainerHeight = headerHeight + footerHeight;
        var totalMapHeight = windowHeight - mapContainerHeight;
        $("#map").css("margin-top", headerHeight);
        $("#map").height(totalMapHeight);
    
        $(window).resize(function(){
            var headerHeight = $("#navMap").outerHeight();
            var footerHeight = $("footer").outerHeight();
            var windowHeight = window.innerHeight;
            var mapContainerHeight = headerHeight + footerHeight;
            var totalMapHeight = windowHeight - mapContainerHeight;
            $("#map").css("margin-top", headerHeight);
            $("#map").height(totalMapHeight);
            map.fitBounds(group1.getBounds());
        });
    
    0 讨论(0)
提交回复
热议问题