[jquery] how to deal with google map inside of a hidden div (Updated picture)

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

This question is related to jquery google-maps google-maps-api-3

The answer is


Or if you use gmaps.js, call:

map.refresh();

when your div is shown.


My solution was:

CSS:

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

jQuery:

$('.map').width(555); // width of map canvas

I had the same issue, the google.maps.event.trigger(map, 'resize') wasn't working for me.

What I did was to put a timer to update the map after putting visible the div...

//CODE WORKING

var refreshIntervalId;

function showMap() {
    document.getElementById('divMap').style.display = '';
    refreshIntervalId = setInterval(function () { updateMapTimer() }, 300);
}

function updateMapTimer() {
    clearInterval(refreshIntervalId);
    var map = new google.maps.Map(....
    ....
}

I don't know if it's the more convenient way to do it but it works!


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.


My solution is very simple and efficient:

HTML

<div class="map-wrap"> 
  <div id="map-canvas"></div>
</div>


CSS

.map-wrap{
  height:0;
  width:0;
  overflow:hidden;
}


Jquery

$('.map-wrap').css({ height: 'auto', width: 'auto' }); //For showing your map
$('.map-wrap').css({ height: 0, width: 0 }); //For hiding your map

use this line of codes when you want to show map.

               $("#map_view").show("slow"); // use id of div which you want to show.
                    var script = document.createElement("script");
                    script.type = "text/javascript";
                    script.src = "https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=initialize";
                    document.body.appendChild(script);

 $("#map_view").show("slow"); // use id of div which you want to show.
     var script = document.createElement("script");
     script.type = "text/javascript";
     script.src = "https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=initialize";
     document.body.appendChild(script);

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.


It's also possible to just trigger the native window resize event.

Google Maps will reload itself automatically:

window.dispatchEvent(new Event('resize'));

First post. My googleMap div was within a container div with {display:none} until tab clicked. Had the same problem as OP. This worked for me:

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

Stick this code inside and at the end of your code where your container div tab is clicked and reveals your hidden div. The important thing is that your container div has to be visible before initialize can be called.

I tried a number of solutions proposed here and other pages and they didn't work for me. Let me know if this works for you. Thanks.


_x000D_
_x000D_
function init_map() {_x000D_
  var myOptions = {_x000D_
    zoom: 16,_x000D_
    center: new google.maps.LatLng(0.0, 0.0),_x000D_
    mapTypeId: google.maps.MapTypeId.ROADMAP_x000D_
  };_x000D_
  map = new google.maps.Map(document.getElementById('gmap_canvas'), myOptions);_x000D_
  marker = new google.maps.Marker({_x000D_
    map: map,_x000D_
    position: new google.maps.LatLng(0.0, 0.0)_x000D_
  });_x000D_
  infowindow = new google.maps.InfoWindow({_x000D_
    content: 'content'_x000D_
  });_x000D_
  google.maps.event.addListener(marker, 'click', function() {_x000D_
    infowindow.open(map, marker);_x000D_
  });_x000D_
  infowindow.open(map, marker);_x000D_
}_x000D_
google.maps.event.addDomListener(window, 'load', init_map);_x000D_
_x000D_
jQuery(window).resize(function() {_x000D_
  init_map();_x000D_
});_x000D_
jQuery('.open-map').on('click', function() {_x000D_
  init_map();_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src='https://maps.googleapis.com/maps/api/js?v=3.exp'></script>_x000D_
_x000D_
<button type="button" class="open-map"></button>_x000D_
<div style='overflow:hidden;height:250px;width:100%;'>_x000D_
  <div id='gmap_canvas' style='height:250px;width:100%;'></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


If you have a Google Map inserted by copy/pasting the iframe code and you don't want to use Google Maps API, this is an easy solution. Just execute the following javascript line when you show the hidden map. It just takes the iframe HTML code and insert it in the same place, so it renders again:

document.getElementById("map-wrapper").innerHTML = document.getElementById("map-wrapper").innerHTML;

jQuery version:

$('#map-wrapper').html( $('#map-wrapper').html() );

The HTML:

....
<div id="map-wrapper"><iframe src="https://www.google.com/maps/..." /></div>
....

The following example works for a map initially hidden in a Bootstrap 3 tab:

<script>
$(document).ready( function() {

    /* Detects when the tab is selected */
    $('a[href="#tab-id"]').on('shown.bs.tab', function() {

        /* When the tab is shown the content of the wrapper
           is regenerated and reloaded */

        $('#map-wrapper').html( $('#map-wrapper').html() ); 

    });
});
</script>

I guess the original question is with a map that is initalized in a hidden div of the page. I solved a similar problem by resizing the map in the hidden div upon document ready, after it is initialized, regardless of its display status. In my case, I have 2 maps, one is shown and one is hidden when they are initialized and I don't want to initial a map every time it is shown. It is an old post, but I hope it helps anyone who are looking.


With jQuery you could do something like this. This helped me load a Google Map in Umbraco CMS on a tab that would not be visible from right away.

function waitForVisibleMapElement() {
    setTimeout(function () {
        if ($('#map_canvas').is(":visible")) {
            // Initialize your Google Map here
        } else {
            waitForVisibleMapElement();
        };
    }, 100);
};

waitForVisibleMapElement();

I've found this to work for me:

to hide:

$('.mapWrapper')
.css({
  visibility: 'hidden',
  height: 0
});

to show:

    $('.mapWrapper').css({
      visibility: 'visible',
      height: 'auto'
    });

If used inside Bootstrap v3 tabs, the following should work:

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

where tab-location is the ID of tab containing map.


I didn't like that the map would load only after the hidden div had become visible. In a carousel, for example, that doesn't really work.

This my solution is to add class to the hidden element to unhide it and hide it with position absolute instead, then render the map, and remove the class after map load.

Tested in Bootstrap Carousel.

HTML

<div class="item loading"><div id="map-canvas"></div></div>

CSS

.loading { display: block; position: absolute; }

JS

$(document).ready(function(){
    // render map //
    google.maps.event.addListenerOnce(map, 'idle', function(){
        $('.loading').removeClass('loading');
    });
}

Upon showing the map I am geocoding a address then setting the maps center. The google.maps.event.trigger(map, 'resize'); did not work for me.

I had to use a map.setZoom(14);

Code below:

document.getElementById('map').style.display = 'block';
var geocoder = new google.maps.Geocoder();
        geocoder.geocode({ 'address': input.value }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);
                var marker2 = new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location
                });
                map.setZoom(14);
                marker2.addListener('dragend', function (event) {
                    $('#lat').val(event.latLng.lat());
                    $('#lng').val(event.latLng.lng());
                });

            }
        });

Add this code before the div or pass it to a js file:

<script>
    $(document).on("pageshow","#div_name",function(){
       initialize();
    });

   function initialize() {
   // create the map

      var myOptions = {
         zoom: 14,
         center: new google.maps.LatLng(0.0, 0.0),
         mapTypeId: google.maps.MapTypeId.ROADMAP
      }
      map = new google.maps.Map(document.getElementById("div_name"), myOptions);
   }


</script>

This event will be triggered after the div loads so it will refresh the map content without having to press F5


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


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
});

How to refresh the map when you resize your div

It's not enough just to call google.maps.event.trigger(map, 'resize'); You should reset the center of the map as well.

var map;

var initialize= function (){
    ...
}

var resize = function () {
    if (typeof(map) == "undefined") {) {
        // initialize the map. You only need this if you may not have initialized your map when resize() is called.
        initialize();
    } else {
        // okay, we've got a map and we need to resize it
        var center = map.getCenter();
        google.maps.event.trigger(map, 'resize');
        map.setCenter(center);
    }
}

How to listen for the resize event

Angular (ng-show or ui-bootstrap collapse)

Bind directly to the element's visibility rather than to the value bound to ng-show, because the $watch can fire before the ng-show is updated (so the div will still be invisible).

scope.$watch(function () { return element.is(':visible'); },
    function () {
        resize();
    }
);

jQuery .show()

Use the built in callback

$("#myMapDiv").show(speed, function() { resize(); });

Bootstrap 3 Modal

$('#myModal').on('shown.bs.modal', function() {
    resize();
})

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to google-maps

GoogleMaps API KEY for testing Google Maps shows "For development purposes only" java.lang.NoClassDefFoundError:failed resolution of :Lorg/apache/http/ProtocolVersion How to import JSON File into a TypeScript file? Googlemaps API Key for Localhost Getting "Cannot call a class as a function" in my React Project ERROR: Google Maps API error: MissingKeyMapError This page didn't load Google Maps correctly. See the JavaScript console for technical details Google Maps API warning: NoApiKeys ApiNotActivatedMapError for simple html page using google-places-api

Examples related to google-maps-api-3

Google Maps shows "For development purposes only" Googlemaps API Key for Localhost ERROR: Google Maps API error: MissingKeyMapError Google Maps API warning: NoApiKeys Google Maps JavaScript API RefererNotAllowedMapError This API project is not authorized to use this API. Please ensure that this API is activated in the APIs Console TypeError: window.initMap is not a function Google maps Marker Label with multiple characters Google Maps how to Show city or an Area outline How to use SVG markers in Google Maps API v3