簡體   English   中英

在 Google 地圖標記對象上添加 infoWindows

[英]Adding infoWindows on Google Maps marker objects

我想在多個標記上添加信息窗口,放置在谷歌地圖上的集群中。 下面是我的代碼。 當我點擊標記時,什么也看不到。 請看一下。

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

在您的.map()您在向其添加EventListener之前返回您的標記,因此永遠不會添加它。

假設這是將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