RichMarker:将click事件侦听器附加到标记数组

时间:2016-06-13 21:29:56

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

这是我的代码块,我push RichMarkers进入数组:

// Populate markers array
for (let i = 0; i < FOUND_OBJECTS_TEST.length; i++) {

    let richMarker = new RichMarker({
        position: new google.maps.LatLng(FOUND_OBJECTS_TEST[i].latitude, FOUND_OBJECTS_TEST[i].longitude),
        map: mainMap,
        draggable: false,
        flat: true,
        anchor: RichMarkerPosition.MIDDLE,
        content: `<figure class="marker_place" data-id="${FOUND_OBJECTS_TEST[i].id}"><img src="svg/map/ic_cat_${FOUND_OBJECTS_TEST[i].type}.svg"><figcaption class="marker_place_caption">${FOUND_OBJECTS_TEST[i].caption}</figcaption></figure>`,
    });

    markers.push(richMarker);
}

我怎样才能为每个标记添加click事件监听器,因此,当点击它时,我会得到这个标记的data-id值?

修改 我可以将event listener添加到标记中,如下所示:

// Populate markers array
for (let i = 0; i < FOUND_OBJECTS_TEST.length; i++) {
    let richMarker = new RichMarker({
           .....
         });

    google.maps.event.addListener(richMarker, 'click', function(event) {
        let id = $(this).data('id'); // returns undefined
        console.log(`clicked on marker ${id}`);
        console.log(this);
    });

    markers.push(richMarker);
}

但是我无法获得标记data-id ...它会记录clicked on marker undefined

2 个答案:

答案 0 :(得分:1)

您可以将data-id添加为marker的属性,然后使用this在单击侦听器函数中检索它。

// Populate markers array
for (let i = 0; i < FOUND_OBJECTS_TEST.length; i++) {
  let richMarker = new RichMarker({
     marker_id: FOUND_OBJECTS_TEST[i].id,
       .....
     });

  google.maps.event.addListener(richMarker, 'click', function(event) {
    console.log(`clicked on marker `+ this.marker_id);
    console.log(this);
  });

  markers.push(richMarker);
}

答案 1 :(得分:0)

k =  markers.push(richMarker);

google.maps.event.addListener(markers[k-1], 'click', function (event) {
                    // you code eg:
                    alert('ok');
            });