功能无法从Google地图中删除标记

时间:2015-08-27 05:10:37

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

以下功能在调用时不会删除标记。为什么?

// Remove existing markers from the Map
function removeMarkers(markersArray) {
    var j,position;

    for (j = 0; j < markersArray.length; j += 1){
        position = new google.maps.Marker({
            position: {lat: markersArray[j][1], lng: markersArray[j][2]}
        });

        position.setMap(null);
    };
};

这是输入函数的数组:

var educationMarkers = [
    ['Grafton Campus, Auckland University', -36.861717, 174.769424],
    ["Auckland Boys' Grammar", -36.872432, 174.768126],
    ["Epsom Girls' Grammar", -36.876177, 174.773639],
    ["St. Peter's College", -36.868412, 174.768575],
    ["ACG Parnell College", -36.863163, 174.778555],
    ["Newmarket Campus, Auckland University", -36.865905, 174.7733]
];

1 个答案:

答案 0 :(得分:0)

您需要保留对所放置标记的参考。

var placedMarkers = [];

function placeMarkers(markersArray) {
    var marker, i, postiion, bounds = new google.maps.LatLngBounds();
    for (i = 0; i < markersArray.length; i += 1) {
        marker = new google.maps.Marker({
            map: map,
            position: {
                lat: markersArray[i][1],
                lng: markersArray[i][2]
            }
        });

        // keep reference of the markers you placed
        placedMarkers.push(marker);

        position = new google.maps.LatLng(markersArray[i][1], markersArray[i][2]);
        bounds.extend(position);
    }
    map.fitBounds(bounds);
};

并在删除标记时,使用您保留的参考数组。

// Remove existing markers from the Map
function removeMarkers() {
    var j,position;

    // loop through reference array you kept.
    for (j = 0; j < placedMarkers.length; j += 1){
        placedMarkers[j].setMap(null);
    };
};