且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

一次只打开一个信息窗口谷歌地图

更新时间:2023-11-18 13:35:16

应该仅创建信息窗口对象的一个​​实例,并使用setContent()方法.

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

首先创建infowindow对象:

First create the infowindow object:

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

然后在其中创建标记并添加click事件监听器的地方:

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

希望这会有所帮助.

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?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk
"></script>