如何从我自己的Google地图中删除标记

时间:2019-04-14 17:32:57

标签: javascript jquery ajax

我正在尝试从自己的Google地图中删除标记,但是我的代码无法正常工作,我也不知道为什么。您想帮我吗?谢谢!

如果我尝试通过console.log(markers.length)调试,函数removeMarkers()中的数据-markers.length仍然为空。

var map;
var markers = [];
var infowindow = new google.maps.InfoWindow();

function initialize() {

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

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

    google.maps.event.addDomListener(document.getElementById('add-markers'), 'click', addMarkers);
    google.maps.event.addDomListener(document.getElementById('remove-markers'), 'click', removeMarkers);
}

function addMarkers() {

    var markerCluster;

    $.ajax({
        type: 'GET',
        url: 'get-places.php',
        dataType: 'json',
        success: function(data) {
            var markers = [];
            $.each(data, function(index, element) {

                var latLng = new google.maps.LatLng(element.lat, element.lng);

                var marker = new google.maps.Marker({
                    position: latLng,
                    map: map,
                    // icon: icon,
                    title: element.title
                });
                markers.push(marker);
                var details = element.name;

                bindInfoWindow(marker, map, infowindow, details);

            });
            markerCluster = new MarkerClusterer(map, markers, {
                imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
            });
        }
    });
}

function removeMarkers() {

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

        markers[i].setMap(null);
    }
}


function bindInfoWindow(marker, map, infowindow, strDescription) {
    google.maps.event.addListener(marker, 'click', function() {
        infowindow.setContent(strDescription);
        infowindow.open(map, marker);
    });
}
initialize();

功能addMarkers()很好,但是removeMarkers()不好。

2 个答案:

答案 0 :(得分:1)

您的全局变量为var markers = [];,但在返回AJAX响应时不会填充此变量。在function addMarkers()中执行的操作是在该函数内部的变量markers中填充该函数的本地变量。

您将需要从var markers = [];中删除function addMarkers(),而要使用全局变量从AJAX响应中填充标记。然后,您将能够在removeMarkers函数中删除标记。

var markers = []; // this is global scope

function addMarkers(){
   var markers = [];  // remove this declaration in this function as it creates local scope


}

function removeMarkers(){
   for (var i = 0; i < markers.length; i++) {
      markers[i].setMap(null);
   }
   markers = []; // do not forget to set this empty
}

答案 1 :(得分:0)

您应该删除markers数组的重新声明。您的removeMarkers函数不知道您正在markers回调中填充的success数组。

var markers = [];

...

success: function(data) {
    var markers = []; // <- remove that redeclaration