在Google地图上恢复已删除的标记

时间:2014-02-21 13:02:15

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

我有一个带有许多标记的地图,我几乎在地图上实现了一种过滤器。当我点击标记时,标记消失,按钮显示在地图顶部以恢复标记 - 这是不起作用的。我试图在用户点击按钮时重新创建标记,但它似乎不起作用。有任何想法吗?这是我的代码:

 function getCrimeByLocation(lat, lng, date){
if(date == null){
    var d = new Date();
    date = d.getFullYear() + '-' + (d.getMonth()+1);
    //hardcoding as of now as jan 2014 data is not there, remove when req
    date = "2013-02";
}
$.getJSON( "http://data.police.uk/api/crimes-street/all-crime?lat="+lat+"&lng="+lng+"&date="+date, function( data ) {
    while(markers.length > 0){
        markers.pop().setMap(null);
    }

    //marking the requested position
    addMyPositionMarker(lat, lng);
    //loop through the data
    $.each(data, function( key, val ) {
        //var myLatlng = new google.maps.LatLng(val.location.latitude, val.location.longitude);
        //create the markers on the map
        var marker = new google.maps.Marker({
            position: new google.maps.LatLng(val.location.latitude, val.location.longitude),
            map: map,
            animation: google.maps.Animation.DROP,
            draggable: false,
            title: val.location.street.name
        });
        markers.push(marker); // saving markers for reference, so that we can remove them later;
        //'click' event to delete the markers from the map
        google.maps.event.addListener(marker, 'click', function(){
            for(var i = 0; i < markers.length; i++){
                markers[i].setMap(null);
            }
            markers.length = 0;
            //Once the markers are deleted, the button shows up
            antisocial.show();
        });
    });

    var antisocial = $('<button>Anti-social behaviour</button>').hide().click(function(){
        //Here I tried to restore the markers, but it doesn't work
        var marker = new google.maps.Marker({
            position: new google.maps.LatLng(val.location.latitude, val.location.longitude),
            map: map,
            animation: google.maps.Animation.DROP,
            draggable: false,
            title: val.location.street.name 
        });
        markers.push(marker);
        //hide the button once it's clicked
        antisocial.hide();
    });
    $('#map-canvas').before(antisocial);

    if(markers.length > 0){
        fitBoundsMap();
    }
});
}

感谢。

1 个答案:

答案 0 :(得分:1)

我认为你只需要将地图设置为null来隐藏标记并将地图重置回原始地图以再次显示它们。

相关问题