Google Map API v3 ~ po prostu zamknąć infowindow?

Próbujesz po prostu zamknąć infowindow?

Mam już tablicę markerów, więc coś takiego byłoby dobre. Dzięki

MyMarkers[i].infowindow.close();
Author: Daniel Vassallo, 2010-06-01

8 answers

Z v3 API , można łatwo zamknąć InfoWindow za pomocą InfoWindow.close() metoda. Po prostu musisz zachować odniesienie do InfoWindow obiektu, którego używasz. Rozważ następujący przykład, który otwiera InfoWindow i zamyka go po 5 sekundach:

<!DOCTYPE html>
<html> 
<head> 
  <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
  <title>Google Maps API InfoWindow Demo</title> 
  <script src="http://maps.google.com/maps/api/js?sensor=false" 
          type="text/javascript"></script>
</head> 
<body>
  <div id="map" style="width: 400px; height: 500px;"></div>

  <script type="text/javascript">
    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 4,
      center: new google.maps.LatLng(-25.36388, 131.04492),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var marker = new google.maps.Marker({
      position: map.getCenter(),
      map: map
    });

    var infowindow = new google.maps.InfoWindow({
      content: 'An InfoWindow'
    });

    infowindow.open(map, marker);

    setTimeout(function () { infowindow.close(); }, 5000);
  </script>
</body>
</html>

Jeśli masz osobny obiekt InfoWindow dla każdego Marker, możesz rozważyć dodanie obiektu InfoWindow jako właściwości swoich obiektów Marker:

var marker = new google.maps.Marker({
  position: map.getCenter(),
   map: map
});

marker.infowindow = new google.maps.InfoWindow({
  content: 'An InfoWindow'
});

Wtedy będziesz mógł otworzyć i zamknąć to InfoWindow jako następuje:

marker.infowindow.open(map, marker);
marker.infowindow.close();

To samo dotyczy tablicy markerów:

var markers = [];

marker[0] = new google.maps.Marker({
  position: map.getCenter(),
   map: map
});

marker[0].infowindow = new google.maps.InfoWindow({
  content: 'An InfoWindow'
});

// ...

marker[0].infowindow.open(map, marker);
marker[0].infowindow.close();
 98
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/doraprojects.net/template/agent.layouts/content.php on line 54
2010-06-01 05:13:24

Lub możesz udostępnić / ponownie użyć tego samego obiektu infoWindow. Zobacz to demo google w celach informacyjnych.

ten sam kod z demo

var Demo = { map: null,  infoWindow: null
};

/**
 * Called when clicking anywhere on the map and closes the info window.
 */
Demo.closeInfoWindow = function() {
  Demo.infoWindow.close();
};

/**
 * Opens the shared info window, anchors it to the specified marker, and
 * displays the marker's position as its content.
 */
Demo.openInfoWindow = function(marker) {
  var markerLatLng = marker.getPosition();
  Demo.infoWindow.setContent([
    '<b>Marker position is:</b><br/>',
    markerLatLng.lat(),
    ', ',
    markerLatLng.lng()
  ].join(''));
  Demo.infoWindow.open(Demo.map, marker);
},

/**
 * Called only once on initial page load to initialize the map.
 */
Demo.init = function() {
  // Create single instance of a Google Map.
  var centerLatLng = new google.maps.LatLng(37.789879, -122.390442);
  Demo.map = new google.maps.Map(document.getElementById('map-canvas'), {
    zoom: 13,
    center: centerLatLng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });

  // Create a single instance of the InfoWindow object which will be shared
  // by all Map objects to display information to the user.
  Demo.infoWindow = new google.maps.InfoWindow();

  // Make the info window close when clicking anywhere on the map.
  google.maps.event.addListener(Demo.map, 'click', Demo.closeInfoWindow);

  // Add multiple markers in a few random locations around San Francisco.
  // First random marker
  var marker1 = new google.maps.Marker({
    map: Demo.map,
    position: centerLatLng
  });

  // Register event listeners to each marker to open a shared info
  // window displaying the marker's position when clicked or dragged.
  google.maps.event.addListener(marker1, 'click', function() {
    Demo.openInfoWindow(marker1);
  });

  // Second random marker
  var marker2 = new google.maps.Marker({
    map: Demo.map,
    position: new google.maps.LatLng(37.787814,-122.40764),
    draggable: true
  });

  // Register event listeners to each marker to open a shared info
  // window displaying the marker's position when clicked or dragged.
  google.maps.event.addListener(marker2, 'click', function() {
    Demo.openInfoWindow(marker2);
  });

  // Third random marker
  var marker3 = new google.maps.Marker({
    map: Demo.map,
    position: new google.maps.LatLng(37.767568,-122.391665),
    draggable: true
  });

  // Register event listeners to each marker to open a shared info
  // window displaying the marker's position when clicked or dragged.
  google.maps.event.addListener(marker3, 'click', function() {
    Demo.openInfoWindow(marker3);
  });
}
 19
Author: Alex Nolasco,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-06-14 18:59:15

Miałem podobny problem. Po prostu dodałem następujący kod:

closeInfoWindow = function() {
    infoWindow.close();
};

google.maps.event.addListener(map, 'click', closeInfoWindow);

Pełny kod js to (powyższy kod to około 15 linijek od dołu):

jQuery(window).load(function() {
if (jQuery("#map_canvas").length > 0){
    googlemap();
}
});

function googlemap() {

jQuery('#map_canvas').css({'height': '400px'});

// Create the map 
// No need to specify zoom and center as we fit the map further down.
var map = new google.maps.Map(document.getElementById("map_canvas"), {
  mapTypeId: google.maps.MapTypeId.ROADMAP,
  streetViewControl: false
});

// Create the shared infowindow with two DIV placeholders
// One for a text string, the other for the StreetView panorama.
var content = document.createElement("div");
var title = document.createElement("div");
var boxText = document.createElement("div");

var myOptions = {
         content: boxText
        ,disableAutoPan: false
        ,maxWidth: 0
        ,pixelOffset: new google.maps.Size(-117,-200)
        ,zIndex: null
        ,boxStyle: { 
          background: "url('"+siteRoot+"images/house-icon-flat.png') no-repeat"
          ,opacity: 1
          ,width: "236px"
          ,height: "300px"
         }
        ,closeBoxMargin: "10px 0px 2px 2px"
        ,closeBoxURL: "http://kdev.langley.com/wp-content/themes/langley/images/close.gif"
        ,infoBoxClearance: new google.maps.Size(1, 1)
        ,isHidden: false
        ,pane: "floatPane"
        ,enableEventPropagation: false
};


var infoWindow = new InfoBox(myOptions);
var MarkerImage = siteRoot+'images/house-web-marker.png';

// Create the markers
for (index in markers) addMarker(markers[index]);
function addMarker(data) {
    var marker = new google.maps.Marker({
        position: new google.maps.LatLng(data.lat, data.lng),
        map: map,
        title: data.title,
        content: data.html,
        icon: MarkerImage
    });
    google.maps.event.addListener(marker, "click", function() {
        infoWindow.open(map, this);         
        title.innerHTML = marker.getTitle();
        infoWindow.setContent(marker.content);
        infoWindow.open(map, marker);
        jQuery(".innerinfo").parent().css({'overflow':'hidden', 'margin-right':'10px'});            
    });
}

// Zoom and center the map to fit the markers
// This logic could be conbined with the marker creation.
// Just keeping it separate for code clarity.
var bounds = new google.maps.LatLngBounds();
for (index in markers) {
    var data = markers[index];
    bounds.extend(new google.maps.LatLng(data.lat, data.lng));
}
map.fitBounds(bounds);
var origcent = new google.maps.LatLng(map.getCenter());
// Handle the DOM ready event to create the StreetView panorama
// as it can only be created once the DIV inside the infowindow is loaded in the DOM.

closeInfoWindow = function() {
        infoWindow.close();
    };

google.maps.event.addListener(map, 'click', closeInfoWindow);

google.maps.event.addListener(infoWindow, 'closeclick', function()
{
    centermap();
});

function centermap()
{
    map.setCenter(map.fitBounds(bounds));
}
}

jQuery(window).resize(function() {
googlemap();
});
 7
Author: kdev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-01-31 20:06:57

Ten też by zadziałał:

google.maps.event.addListener(marker, 'click', function() {
                if(!marker.open){
                    infowindow.open(map,marker);
                    marker.open = true;
                }
                else{
                    infowindow.close();
                    marker.open = false;
                }
            });

Który otworzy infoWindow po kliknięciu, zamknij go po kliknięciu, jeśli został otwarty.

Również widząc rozwiązanie Logana, te 2 można połączyć w to:

google.maps.event.addListener(marker, 'click', function() {
                if(!marker.open){
                    infowindow.open(map,marker);
                    marker.open = true;
                }
                else{
                    infowindow.close();
                    marker.open = false;
                }
                google.maps.event.addListener(map, 'click', function() {
                    infowindow.close();
                    marker.open = false;
                });
            });

Który otworzy infoWindow po kliknięciu na niego, zamknij go po kliknięciu na niego i został otwarty, i zamknij go, jeśli zostanie kliknięty w dowolnym miejscu na mapie, a infoWindows został otwarty.

 4
Author: Mahir Zukic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-11-05 17:44:23

Możesz po prostu dodać słuchacz kliknięć na mapie wewnątrz funkcji, która tworzy InfoWindow

google.maps.event.addListener(marker, 'click', function() {
    var infoWindow = createInfoWindowForMarker(marker);
    infoWindow.open(map, marker);
    google.maps.event.addListener(map, 'click', function() {
        infoWindow.close();
    });
});
 1
Author: Logan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-09-04 00:05:36

Poniższy detektor zdarzeń rozwiązał to ładnie dla mnie, nawet gdy używam wielu znaczników i okien informacyjnych:

//Add click event listener
google.maps.event.addListener(marker, 'click', function() {
  // Helper to check if the info window is already open
  google.maps.InfoWindow.prototype.isOpen = function(){
      var map = infoWindow.getMap();
      return (map !== null && typeof map !== "undefined");
  }
  // Do the check
  if (infoWindow.isOpen()){
    // Close the info window
    infoWindow.close();
  } else {
    //Set the new content
    infoWindow.setContent(contentString);
    //Open the infowindow
    infoWindow.open(map, marker);
  }
});
 0
Author: Craig van Tonder,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-11 11:36:28

Możemy użyć infowindow.close( map); aby zamknąć wszystkie okna informacji, jeśli już zainicjować okno informacji za pomocą infowindow = new google.mapy.InfoWindow ();

 0
Author: Naushad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-19 12:28:16
infowindow.open(null,null);

Zamknie otwarty infowindow. Będzie działać tak samo jak

 -2
Author: Janki,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-08-31 14:53:31