【问题标题】:How to find out which marker was clicked from an array of google map markers如何找出从谷歌地图标记数组中单击了哪个标记
【发布时间】:2017-01-24 01:16:59
【问题描述】:

我有一组标记对象markers。然后我使用 for 循环向它们添加事件侦听器。但是,我似乎无法弄清楚如何确定点击了哪些标记。

这是我现在拥有的代码:

 for(var i = 0; i < this.markers.length; i++) //adds listener to all markers
 {
      google.maps.event.addListener(this.markers[i], "click", () =>
      {
            //need to get access to which marker was clicked
      }); 
 }

我尝试将参数传递给箭头函数,但似乎没有任何效果。有任何想法吗?只要函数可以返回正确标记的索引,就不需要箭头函数。

【问题讨论】:

  • 如果你将回调设为函数而不是箭头函数,this 将是被点击的标记

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


【解决方案1】:

请阅读documentation

这是一个工作示例:

function initialize() {

  var mapOptions = {
    zoom: 5,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center: new google.maps.LatLng(1, 1)
  };

  var locations = [
    [new google.maps.LatLng(0, 0), 'Marker 1', 'Infowindow content for Marker 1'],
    [new google.maps.LatLng(0, 1), 'Marker 2', 'Infowindow content for Marker 2'],
    [new google.maps.LatLng(0, 2), 'Marker 3', 'Infowindow content for Marker 3'],
    [new google.maps.LatLng(1, 0), 'Marker 4', 'Infowindow content for Marker 4'],
    [new google.maps.LatLng(1, 1), 'Marker 5', 'Infowindow content for Marker 5'],
    [new google.maps.LatLng(1, 2), 'Marker 6', 'Infowindow content for Marker 6']
  ];

  var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

  var infowindow = new google.maps.InfoWindow();

  for (var i = 0; i < locations.length; i++) {

    var marker = new google.maps.Marker({
      position: locations[i][0],
      map: map,
      title: locations[i][1]
    });

    google.maps.event.addListener(marker, 'click', (function(marker, i) {

      return function() {
        infowindow.setContent(locations[i][2]);
        infowindow.open(map, marker);
      }

    })(marker, i));
  }
}

initialize();
#map-canvas {
  height: 200px;
}
<div id="map-canvas"></div>

<script src="https://maps.googleapis.com/maps/api/js"></script>

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-06
  • 2012-09-27
  • 2013-12-04
  • 2019-06-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多