cómo lidiar con google map dentro de un div oculto (Imagen actualizada)


Tengo una página y un mapa de Google está dentro de un div oculto al principio. Luego muestro el div después de hacer clic en un enlace, pero solo aparece la parte superior izquierda del mapa.

He intentado que este código se ejecute después del clic:

    map0.onResize();

O:

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

Cualquier idea. aquí hay una imagen de lo que veo después de mostrar el div con el mapa oculto en él.texto alt

Author: Galen, 2010-10-31

23 answers

Acabo de probarlo yo mismo y así es como me acerqué a él. Bastante sencillo, hágamelo saber si necesita alguna aclaración

HTML

<div id="map_canvas" style="width:700px; height:500px; margin-left:80px;" ></div>
<button onclick="displayMap()">Show Map</button>

CSS

<style type="text/css">
#map_canvas {display:none;}
</style>

Javascript

<script>
function displayMap()
{
    document.getElementById( 'map_canvas' ).style.display = "block";
    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( "map_canvas" ),myOptions );
}
</script>
 103
Author: Philar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-14 19:08:03

Estaba teniendo el mismo problema y descubrí que cuando mostrar el div, llamar google.maps.event.trigger(map, 'resize'); y parece resolver el problema para mí.

 125
Author: Eric,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-24 17:44:28
google.maps.event.trigger($("#div_ID")[0], 'resize');

Si no tienes el mapa de variables disponible, debería ser el primer elemento (a menos que hayas hecho algo estúpido) en el div que contenga GMAP.

 26
Author: C S N,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-12-08 22:04:47

Tenía un mapa de Google dentro de una pestaña Bootstrap, que no se mostraba correctamente. Esta era mi dosis.

// 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
});
 13
Author: Simon East,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-13 05:34:50

Cómo actualizar el mapa cuando cambia el tamaño de su div

No es suficiente con llamar a google.maps.event.trigger(map, 'resize'); También debes restablecer el centro del mapa.

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

Cómo escuchar el evento redimensionar

Angular (ng-show o ui-bootstrap collapse)

Enlazar directamente a la visibilidad del elemento en lugar del valor vinculado a ng-show, porque el watch watch puede disparar antes de que el ng-show se actualice (por lo que el div seguirá siendo invisible).

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

JQuery .mostrar()

Utilice el callback incorporado

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

Bootstrap 3 Modal

$('#myModal').on('shown.bs.modal', function() {
    resize();
})
 7
Author: civmeup,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-02 01:24:19

Tuve el mismo problema, el google.maps.event.trigger(map, 'resize') no estaba funcionando para mí.

Lo que hice fue poner un temporizador para actualizar el mapa después de poner visible el 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(....
    ....
}

No se si es la forma más conveniente de hacerlo pero funciona!

 5
Author: Carlos,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-24 17:49:36

Si tiene un Mapa de Google insertado copiando / pegando el código iframe y no desea utilizar la API de Google Maps , esta es una solución fácil. Simplemente ejecute la siguiente línea de javascript cuando muestre el mapa oculto. Simplemente toma el código HTML iframe y lo inserta en el mismo lugar, por lo que vuelve a renderizar:

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

Versión de jQuery:

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

El HTML:

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

El siguiente ejemplo funciona para un mapa oculto inicialmente en una pestaña Bootstrap 3:

<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>
 5
Author: Gustavo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-03 02:12:08

También es posible activar el evento de redimensionamiento de ventana nativo.

Google Maps se recargará automáticamente:

window.dispatchEvent(new Event('resize'));
 5
Author: Philip Miglinci,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-10 14:14:54

Con jQuery podrías hacer algo como esto. Esto me ayudó a cargar un Mapa de Google en Umbraco CMS en una pestaña que no sería visible de inmediato.

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

waitForVisibleMapElement();
 4
Author: Dennis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-18 11:30:43

Mi solución es muy simple y eficiente:

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
 3
Author: midishero,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-14 17:14:08

O si utiliza gmaps.js , call:

map.refresh();

Cuando se muestra su div.

 3
Author: Eric Saboia,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-07 15:42:52

Supongo que la pregunta original es con un mapa que se inicia en un div oculto de la página. Resolví un problema similar al cambiar el tamaño del mapa en el div oculto en el documento listo, después de que se inicializa, independientemente de su estado de visualización. En mi caso, tengo 2 mapas, uno es, y se oculta cuando se inicializan y no quiero inicial de un mapa cada vez que se muestra. Es un post antiguo, pero espero que ayude a cualquiera que esté buscando.

 2
Author: KYLO,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-17 19:01:04

He encontrado que esto funciona para mí:

Para ocultar:

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

Para mostrar:

    $('.mapWrapper').css({
      visibility: 'visible',
      height: 'auto'
    });
 2
Author: Victor S,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-06 17:27:28

Si se usa dentro de las pestañas Bootstrap v3, lo siguiente debería funcionar:

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

Donde tab-location es el ID de tab que contiene map.

 2
Author: Nirmal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-09 05:31:57

Tal y como John Doppelmann y HoffZ han indicado, junte todo el código de la siguiente manera en su div que muestra la función o el evento onclick:

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

Funcionó perfectamente para mí

 2
Author: Victor Tarango,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-22 23:48:23

Mi solución fue:

CSS:

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

JQuery:

$('.map').width(555); // width of map canvas
 0
Author: user2385294,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-25 13:36:40

No me gustó que el mapa se cargara solo después de que el div oculto se hiciera visible. En un carrusel, por ejemplo, eso no funciona.

Esta mi solución es agregar clase al elemento oculto para mostrarlo y ocultarlo con position absolute en su lugar, luego renderizar el mapa y eliminar la clase después de cargar el mapa.

Probado en Carrusel Bootstrap.

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');
    });
}
 0
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-18 08:36:35

Utilice esta línea de códigos cuando desee mostrar mapa.

               $("#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);
 0
Author: Ravi Darji,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-02 06:26:44
 $("#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);
 0
Author: Ravi Darji,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-02 06:32:54

Primer mensaje. Mi div GoogleMap estaba dentro de un div contenedor con {display: none} hasta que se hizo clic en la pestaña. Tenía el mismo problema que OP. Esto funcionó para mí:

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

Coloque este código dentro y al final de su código donde se hace clic en la pestaña div del contenedor y revela su div oculto. Lo importante es que su div de contenedor tiene que ser visible antes de que se pueda llamar a initialize.

Probé una serie de soluciones propuestas aquí y otras páginas y no funcionaron para mí. Házmelo saber si esto te funciona. Gracias.

 0
Author: Leonard,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-21 02:36:39

Agregue este código antes del div o páselo a un archivo js:

<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>

Este evento se activará después de que se cargue el div, por lo que actualizará el contenido del mapa sin tener que presionar F5

 0
Author: Balibrera,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-19 05:35:12

Al mostrar el mapa estoy geocodificando una dirección y luego configurando el centro de mapas. El google.maps.event.trigger(map, 'resize'); no funcionó para mí.

Tuve que usar un map.setZoom(14);

Código a continuación:

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

            }
        });
 0
Author: Andrew,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-10 09:26: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>
 -1
Author: user6414609,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-02 18:37:29