首页 文章

处理多个标记时,在标记点击事件后显示折线 .

提问于
浏览
-1

我正在开发一个使用Google Maps API v3的网络应用程序 . 我在一小时内创建了大约400个标记,这些标记正在currentDisplayedMarkers []中推送 . 对于每个标记,我创建一个包含其过去位置的折线 . 这很好用 . 但是,我想仅在单击特定标记时显示Polyline作为标记 . 我创建了一个名为addClickHandler的函数,在其中我为每个标记定义了onClick监听器 . 单击标记时,应将折线添加到 Map 中 .

单击标记时,折线不会显示在 Map 上 . 你对我做错了什么有什么想法吗?

if (!found)
                   {
                       var LatLng = { lat: data[i].Plots[0].Latitude, lng: data[i].Plots[0].Longitude };
                       createMarker(LatLng, 90, data[i].TrackNumber);
                       drawPolyline(data[i].Plots);
                   }
function createMarker(markerLatLng, direction, id) {
var iconImage = {
    path: 'M265.54,0H13.259C5.939,0,0.003,5.936,0.003,13.256v252.287c0,7.32,5.936,13.256,13.256,13.256H265.54c7.318,0,13.256-5.936,13.256-13.256V13.255C278.796,5.935,272.86,0,265.54,0z M252.284,252.287H26.515V26.511h225.769V252.287z',
    strokeColor: '#800000',
    scale: 0.05,
    fillOpacity: 1,
    strokeWeight: 1
}
//draw the marker and attach it to the map
marker = new google.maps.Marker({
    position: markerLatLng,
    map: map,
    icon: iconImage,
    draggable: false
});
//add aditional properties to the marker
marker.metadata = {
    id: id
};

//add the marker to the markers array
currentlyDisplayedMarkers.push(marker);
for (var j = 0; j < currentlyDisplayedMarkers.length; j++) {
    var pathMarker = currentlyDisplayedMarkers[j];
    addClickHandler(pathMarker);
}
}
function addClickHandler(pathMarker) {
google.maps.event.addListener(pathMarker, 'click', function () {
    flightPath.setMap(map);
});
}

1 回答

  • 1

    您应该将下面的块移动到 createMarker() 函数的外部 .

    for (var j = 0; j < currentlyDisplayedMarkers.length; j++) {
        var pathMarker = currentlyDisplayedMarkers[j];
        addClickHandler(pathMarker);
    }
    

    无需遍历当前的DisplayedMakers集合,只需在每次创建一个标记时将eventhandler添加到每个标记 .

    只需将eventhandler添加到您刚刚创建的那个标记即可 .

    解决方案:将迭代移动到标记创建函数之外,或者只为标记创建函数中创建的标记添加一个事件处理程序 .

相关问题