如何向Map marker [] array

时间:2017-06-29 19:50:20

标签: javascript google-maps google-maps-api-3

我有一个谷歌地图实现,使用几个函数调用和一个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); 
      }

1 个答案:

答案 0 :(得分:1)

您没有向数组添加事件,您必须将其添加到数组中的每个元素。您可以使用.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); 
  }