如何使用谷歌地图API在标记上设置弹出窗口

How to set a popup on markers with Google Maps API?

本文关键字:设置 窗口 何使用 谷歌地图 API      更新时间:2023-09-26

我有这段代码,用于显示和设置所有标记。如何使用此代码添加带有标记信息的弹出窗口?我在文本上添加了"I"变量,但它在所有弹出的标记上设置了"test-723",其中723是"I"的最后一个值。怎么了?

for (var i = 0; i < arraylng.length-1; i++) {
  var marker = new google.maps.Marker({
    position: new google.maps.LatLng(arraylng[i], arraylat[i])
  });
  var infowindow = new google.maps.InfoWindow({
    content: " "
  });
  google.maps.event.addListener(marker, 'click', function() {
    infowindow.setContent('test: ' + i + '');
    infowindow.open(map, this);
  });
  markers.push(marker);
}

首先,将循环条件更改为i < arraylng.length。现在它没有捕获数组的最后一个元素。

JavaScript变量使用函数范围,因此需要为每个标记侦听器调用一个函数来创建正确的变量引用。您可以使用匿名函数,如这里所示,或者定义一个用于创建点击侦听器的函数:

多信息窗口:

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

很可能您不希望同时打开多个InfoWindow,因为必须单击关闭x会很烦人。然后,您只需要一个InfoWindow对象,并在单击标记时设置内容:

单一信息窗口:

...
  var infowindow = new google.maps.InfoWindow();
  for (var i = 0; i < arraylng.length-1; i++) {
    var marker = new google.maps.Marker({
      position: new google.maps.LatLng(arraylng[i], arraylat[i]),
      map: map
    });
    makeInfoWindowEvent(map, infowindow, "test" + i, marker);
    markers.push(marker);
  }
}
function makeInfoWindowEvent(map, infowindow, contentString, marker) {
  google.maps.event.addListener(marker, 'click', function() {
    infowindow.setContent(contentString);
    infowindow.open(map, marker);
  });
}

这是您可以添加弹出内容的区域

var infowindow = new google.maps.InfoWindow({
                content: "Add your popup content here"
              });

这是为了显示弹出的

marker.addListener('click', function() {
          infowindow.open(map, marker);
        });

下面的代码显示了它是如何工作和使用的。

features.forEach(function(feature) {
          var infowindow = new google.maps.InfoWindow({
                    content: "Add your popup content here"
                  });
            var marker = new google.maps.Marker({
            position: new google.maps.LatLng(lat,long),
            icon: "image.png",
            /*icon: icons[feature.type].icon,*/
            title: "Title for marker",
            map: map
          });
          marker.addListener('click', function() {
          infowindow.open(map, marker);
        });
        });

var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
              position: myLatLng,
              ....
              content: point[4]
          });
google.maps.event.addListener(marker, 'click', function() {
            infowindow.setContent(this.content);
            infowindow.open(map, this);
          });

循环内的代码。这对我来说非常有效。

这是因为变量i不在循环中使用,而是在单击标记时使用——然后i等于最后一个索引+1…addListener是异步的,而不是同步的。

取下infowindow.setContent('test: ' + i + '');,用content: 'test: ' + i替换content: " "。这应该可以解决你的问题。