簡體   English   中英

如何將事件監聽器添加到Map marker []數組

[英]How to add event listener to Map marker[ ] array

我有一個Google Map實現,它使用幾個函數調用和marker []數組在地圖上放置圖釘。

它很好用,但是我無法弄清楚如何在函數中添加onClick事件或其他類型的事件偵聽器,因為它沒有明確定義標記變量。

我在哪里可以添加這樣的內容?:

google.maps.event.addListener(markers, 'click', function() {
window.location.href = this.url;};

這是我的基本地圖代碼和功能:

var pinlocations = [
  ['1', {lat: 30.266758, lng: -97.739080}, 12, '/establishments/1111'],
  ['2', {lat: 30.267178, lng: -97.739050}, 11, '/establishments/1222'],
  ['3', {lat: 30.267458, lng: -97.741231}, 10, '/establishments/1333'],
  ['4', {lat: 30.388880, lng: -97.892276}, 9, '/establishments/1444']
];

      var markers = [];
      var map;

      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          zoom: 12,
          center: {lat: 30.267178, lng: -97.739050}
        });

      }

      function drop() {
        clearMarkers();
        for (var i = 0; i < pinlocations.length; i++) {
            var place = pinlocations[i];
            addMarkerWithTimeout(place[1], place[0], place[2], place[3], i * 200);
        }
      }

      function addMarkerWithTimeout(position, title, zindex, url, timeout) {
        window.setTimeout(function() {
          markers.push(new google.maps.Marker({
            position: position,
            map: map,
            title: title,
            zIndex: zindex,
            url: url,
            animation: google.maps.Animation.DROP
          }));  
        }, timeout); 
      }

您無需將事件添加到數組中,而必須將其添加到數組中的每個元素中。 您可以使用.forEach()數組方法執行此操作:

// Iterate the markers array
markers.forEach(function(marker){
  // Set up a click event listener for each marker in the array
  marker.addListener('click', function() {
    window.location.href = marker.url;
  });
});

或者,您可以采用另一種方法,並在創建每個標記時添加事件。

  function addMarkerWithTimeout(position, title, zindex, url, timeout) {
    window.setTimeout(function() {
      markers.push(new google.maps.Marker({
        position: position,
        map: map,
        title: title,
        zIndex: zindex,
        url: url,
        animation: google.maps.Animation.DROP
      }).addListener('click', function() {
        window.location.href = this.url;
      });  
    }, timeout); 
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM