Open only one infowindow at a time google maps

南楼画角 提交于 2019-12-01 00:21:34

You should create only one instance of the infowindow object and use the setContent() method.

First create the infowindow object:

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

Then where you create your marker and add the click event listener:

google.maps.event.addListener(marker, 'click', function () {

    infowindow.setContent('set the infowindow content here');
    infowindow.open(map, marker);
});

Hope this helps.

var map = null;
var infowindow = new google.maps.InfoWindow();

function initialize() {

  var myOptions = {
    zoom: 8,
    center: new google.maps.LatLng(43.907787, -79.359741),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }

  map = new google.maps.Map(document.getElementById("map_canvas"),
    myOptions);

  google.maps.event.addListener(map, 'click', function() {
    infowindow.close();
  });

  // Add markers to the map
  // Set up three markers with info windows

  var point;

  point = new google.maps.LatLng(43.65654, -79.90138);
  createMarker(point, 'This is point 1');

  point = new google.maps.LatLng(43.91892, -78.89231);
  createMarker(point, 'This is point 2');

  point = new google.maps.LatLng(43.82589, -79.10040);
  createMarker(point, 'This is point 3');
}

function createMarker(latlng, html) {

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

  google.maps.event.addListener(marker, 'click', function() {

    infowindow.setContent(html);
    infowindow.open(map, marker);
  });
}

initialize();
#map_canvas {
  height: 200px;
}
<div id="map_canvas"></div>
<script src="https://maps.googleapis.com/maps/api/js"></script>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!