如何在谷歌地图上逐个删除标记

5
我已经创建了一个标记数组。我使用这个标记数组来监听'click'事件,并在Google地图上放置标记,同时创建函数来'清除所有标记','重新显示所有标记'和'删除所有标记'。
问题是,我该如何以一种能够逐个清除或删除标记的方式来实现?原因是,如果我不小心将标记放置在我不想要的位置上,我会想要清除/删除它。如果我要清除/删除特定的标记,之前绘制的其他标记也会被清除/删除...
我的代码:
//Initialize the map
function initialize() {
    var myLatlng = new google.maps.LatLng(2,110);
    var myOptions = {
        zoom: 3,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.HYBRID
    };

    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    infowindow = new google.maps.InfoWindow({
        content: "loading..."
    });
}

function changeForm(the_form) {
    window.location = the_form;
}


//Listen for click
function marker() {
    google.maps.event.addListener(map, 'click', function(event) {
        addMarker(event.latLng);
    });
}

// Place markers in by click
function addMarker(location) {
    marker = new google.maps.Marker({
        position: location,
        map: map,
        title:"Specified Location",
        icon: 'images/greenPoint.png'
    });
    markersArray.push(marker);
}

// Deletes all markers in the array by removing references to them
function deleteOverlays() {
    if (markersArray) {
        for (i in markersArray) {
            markersArray[i].setMap(null);
        }
        markersArray.length = 0;
    }
}

// Removes the overlays from the map, but keeps them in the array
function clearOverlays() {
    if (markersArray) {
        for (i in markersArray) {
            markersArray[i].setMap(null);
        }
    }
}

// Shows any overlays currently in the array
function showOverlays() {
    if (markersArray) {
        for (i in markersArray) {
            markersArray[i].setMap(map);
        }
    }
}
1个回答

4
当您创建标记时,不要将它们全部推送到标记数组markersArray中,而是可以基于它们的Lat/Lng(或更好的是某种ID)存储它们,然后在每个标记上设置事件处理程序,以便在单击时从标记列表中删除自身。
我不确定能否在google.maps.Marker对象中存储任意信息,但您始终可以创建自己的对象,该对象具有ID和google.maps.Marker对象作为其成员:
function myMarker(id, location) {
    this.id = id;
    this.marker = new google.maps.Marker({...});
}

那么markersArray[id] = new myMarker(myId, myLocation)将允许您根据任意ID存储所有标记。然后,您可以分配我在this.marker上描述的处理程序,以从markersArray和地图中删除自己。

另一种方法是根据它们的Lat/Lngs存储标记,因此您的markersArray将保存以下方式的标记:

markersArray[location.lat][location.lng] = new google.maps.Marker({...});

当点击标记时,您可以使用事件处理程序获取标记的经纬度,并以此从数组和地图中删除它。

如果需要更多细节,请告诉我。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接