Tener solo una InfoWindow abierta en Google Maps API v3


Necesito tener solo una ventana de información abierta en mi mapa de Google. Necesito cerrar todas las demás ventanas de información antes de abrir una nueva.

¿Alguien puede mostrarme cómo hacer esto?

Author: Connor, 2009-12-09

10 answers

Necesita crear solo un objeto InfoWindow, mantener una referencia a él y reutilizarlo para todos los marcadores. Citando los documentos de la API de Google Maps :

Si solo desea que se muestre una ventana de información a la vez (como es el comportamiento en Google Maps), solo necesita crear una ventana de información, que puede reasignar a diferentes ubicaciones o marcadores en eventos de mapa (como clics de usuario).

Por lo tanto, es posible que simplemente desee crear el objeto InfoWindow justo después de inicialice su mapa y, a continuación, maneje los controladores de eventos click de sus marcadores de la siguiente manera. Digamos que tienes un marcador llamado someMarker:

google.maps.event.addListener(someMarker, 'click', function() {
   infowindow.setContent('Hello World');
   infowindow.open(map, this);
});

Entonces el InfoWindow debe cerrarse automáticamente cuando haga clic en un nuevo marcador sin tener que llamar al método close().

 144
Author: Daniel Vassallo,
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-08-12 13:28:50

Cree su infowindow fuera del ámbito para que pueda compartirlo.

Aquí hay un ejemplo simple:

var markers = [AnArrayOfMarkers];
var infowindow = new google.maps.InfoWindow();

for (var i = 0, marker; marker = markers[i]; i++) {
  google.maps.event.addListener(marker, 'click', function(e) {
    infowindow.setContent('Marker position: ' + this.getPosition());
    infowindow.open(map, this);
  });
}
 27
Author: skarE,
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
2010-08-05 07:14:38

Tuve el mismo problema pero la mejor respuesta no lo resolvió completamente, lo que tuve que hacer en mi declaración for fue usar el esto relacionado con mi marcador actual. Tal vez esto ayude a alguien.

for(var i = 0; i < markers.length; i++){
    name = markers[i].getAttribute("name");
    address = markers[i].getAttribute("address");        
    point = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")));                                     
    contentString = '<div style="font-family: Lucida Grande, Arial, sans-serif;>'+'<div><b>'+ name +'</b></div>'+'<div>'+ address +'</div>';                    
    marker = new google.maps.Marker({                       
        map: map,
        position: point,
        title: name+" "+address,
        buborek: contentString 
    });                                     
    google.maps.event.addListener(marker, 'click', function(){
        infowindow.setContent(this.buborek); 
        infowindow.open(map,this); 
    });                                                         
    marker.setMap(map);                 
}
 12
Author: Feco,
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
2011-09-01 10:11:28

Un poco tarde, pero me las arreglé para tener solo una infowindow abierta por maken infowindow una variable global.

var infowindow = new google.maps.InfoWindow({});

Luego dentro del listner

infowindow.close();
infowindow = new google.maps.InfoWindow({   
    content: '<h1>'+arrondissement+'</h1>'+ gemeentesFiltered                           
});

infowindow.open(map, this);
 3
Author: user2827958,
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-06-08 09:26:19

Declare un globar var selectedInfoWindow; y úselo para mantener la ventana de información abierta:

var infoWindow = new google.maps.InfoWindow({
    content: content
});

// Open the infowindow on marker click
google.maps.event.addListener(marker, "click", function() {
    //Check if there some info window selected and if is opened then close it
    if (selectedInfoWindow != null && selectedInfoWindow.getMap() != null) {
        selectedInfoWindow.close();
        //If the clicked window is the selected window, deselect it and return
        if (selectedInfoWindow == infoWindow) {
            selectedInfoWindow = null;
            return;
        }
    }
    //If arrive here, that mean you should open the new info window 
    //because is different from the selected
    selectedInfoWindow = infoWindow;
    selectedInfoWindow.open(map, marker);
});
 3
Author: IgniteCoders,
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
2018-02-26 14:44:13

Debe realizar un seguimiento de su objeto InfoWindow anterior y llamar al método close cuando maneje el evento click en un nuevo marcador.

N. B No es necesario llamar a close en el objeto ventana de información compartida, llamando a open con un marcador diferente cerrará automáticamente el original. Ver La respuesta de Daniel para más detalles.

 0
Author: RedBlueThing,
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-05-23 12:10:26

Básicamente desea una función que mantenga la referencia a one new InfoBox() = > delegar el evento onclick. Mientras crea sus marcadores (en un bucle) use bindInfoBox(xhr, map, marker);

// @param(project): xhr : data for infoBox template
// @param(map): object : google.maps.map
// @param(marker): object : google.maps.marker
bindInfoBox: (function () {
    var options = $.extend({}, cfg.infoBoxOptions, { pixelOffset: new google.maps.Size(-450, -30) }),
        infoBox = new window.InfoBox(options);

    return function (project, map, marker) {
        var tpl = renderTemplate(project, cfg.infoBoxTpl); // similar to Mustache, Handlebars

        google.maps.event.addListener(marker, 'click', function () {
            infoBox.setContent(tpl);
            infoBox.open(map, marker);
        });
    };
}())

var infoBox se asigna asíncronamente y se guarda en memoria. Cada vez que llame a bindInfoBox() se llamará a la función return en su lugar. También es útil para pasar el infoBoxOptions solo una vez!

En mi ejemplo he tenido que añadir un param extra a la map ya que mi inicialización se retrasa por eventos de tabulación.

Infoboxopciones

 0
Author: Tim Vermaelen,
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-04-24 09:59:51

Aquí hay una solución que no necesita crear solo una InfoWindow para reutilizarla. Puede continuar creando muchas InfoWindows, lo único que necesita es construir una función closeAllInfoWindows, y llamarla antes de abrir una nueva infowindow. Por lo tanto, manteniendo su código, solo necesita:

  1. Crear una matriz global para almacenar todas las ventanas de información

    var infoWindows = [];
    
  2. Almacena cada nueva InfoWindow en el array, justo después de la InfoWindow = new...

    infoWindows.push(infoWindow);
    
  3. Crear la función closeAllInfoWindows

    function closeAllInfoWindows() {
        for (var i=0;i<infoWindows.length;i++) {
            infoWindows[i].close();
        }
    }
    
  4. En tu código, llama a closeAllInfoWindows () justo antes de abrir la ventana de información.

Saludos,

 0
Author: Jortx,
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-08-11 23:28:33

Resuelto de esta manera:

function window(content){
    google.maps.event.addListener(marker,'click', (function(){
        infowindow.close();
        infowindow = new google.maps.InfoWindow({
            content: content
        });
        infowindow.open(map, this);
    }))
}
window(contentHtml);
 -1
Author: Bilal Boulaich,
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
2018-02-26 13:53:47

Google Maps le permite tener una sola ventana de información abierta. Así que si abre una nueva ventana, entonces la otra se cierra automáticamente.

 -4
Author: Kimmo Puputti,
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
2009-12-09 17:58:17