简体   繁体   English

在 Google 地图标记对象上添加 infoWindows

[英]Adding infoWindows on Google Maps marker objects

I want to add info windows on multiple markers, placed in clusters on google maps.我想在多个标记上添加信息窗口,放置在谷歌地图上的集群中。 Here is my code below.下面是我的代码。 When I tap on a marker, can not see anything.当我点击标记时,什么也看不到。 Have a look please.请看一下。

function initMap() {
  var map = new google.maps.Map(document.getElementById("map"), {
    zoom: 10,
    center: { lat: 62.601, lng: 29.7636 },
  });
  var infowindow = new google.maps.InfoWindow();
  var markers = locations.map(function (location, i) {
    return new google.maps.Marker({
      position: location,
      title: "test",
    });
    google.maps.event.addListener(markers, "click", function () {
      infowindow.setContent("<h3>" + "testing" + "</h3>");
      infowindow.open(map, this);
    });
  });
  // Add a marker clusterer to manage the markers.
  var markerCluster = new MarkerClusterer(map, markers, {
    imagePath:
      "https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m",
  });
}

In your .map() you are returning your marker before adding the EventListener to it, so it will never be added.在您的.map()您在向其添加EventListener之前返回您的标记,因此永远不会添加它。

Assuming this is the correct way to add an EventListener to a marker, do the following - Temp save it and return it after you added the EventListener like in this snippet:假设这是将EventListener添加到标记的正确方法,请执行以下操作 - 临时保存它并在添加EventListener后返回它,如以下代码段所示:

function initMap() {
  var map = new google.maps.Map(document.getElementById("map"), {
    zoom: 10,
    center: { lat: 62.601, lng: 29.7636 },
  });
  var markers = locations.map(function (location, i) {
    const marker = new google.maps.Marker({ // temp save
      position: location,
      title: "test",
    });

    google.maps.event.addListener(marker, "click", function () { // add eventlistener to marker
      var infowindow = new google.maps.InfoWindow(); // probably also move infoWindow initialization in here
      infowindow.setContent("<h3>" + "testing" + "</h3>");
      infowindow.open(map, this);
    });

    return marker; // return after
  });
  // Add a marker clusterer to manage the markers.
  var markerCluster = new MarkerClusterer(map, markers, {
    imagePath:
      "https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m",
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM