Remove one of many markers on Google maps with javascript

主宰稳场 提交于 2019-12-01 06:20:28

问题


I currently add markers to the map using the code below. I'd like to be able to remove any one at any time by pushing a javascript command. Is this possible?

ex. place 5 markers.. removed the 3rd one while keeping the other 4.

$('#map').show();
var geocoder = new google.maps.Geocoder();
var address = document.getElementById("address").value +", " + document.getElementById("city").value;

geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
    var lat = results[0].geometry.location.lat();
    var lng = results[0].geometry.location.lng();
    locationsall[counter] = new Array();
    locationsall[counter][0] = address;
    locationsall[counter][1] = lat;
    locationsall[counter][2] = lng;
    var mapOptions = {
        zoom: 13,
        center: new google.maps.LatLng(lat, lng),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }

var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var marker, i;
for (i = 0; i < locationsall.length; i++) {  
    marker = new google.maps.Marker({
    position: new google.maps.LatLng(locationsall[i][1], locationsall[i][2]),
    map: map,
    title: 'You are here!'
    });
}
counter++;
} else {
    alert("Geocode was not successful for the following reason: " + status);
}

}); }

Edit 1:

        }).text("Remove").click(function() {
    var index2 = $tr2.index();
    $("#locationDeals input[type='hidden']").each(function() {
        this.name = this.name.replace(/\[(\d+)\]/, function(str2, number2) {
          return "[" + (+number2 > index2 - 1 ? number2 - 1 : number2) + "]";
        });
    });
    //locationsall[locations.indexOf(location)].setMap(null);
    $tr2.remove();
    locations.splice(locations.indexOf(location), 1);
    return false;
        }).appendTo($tdRemoveRow2);

回答1:


Outside of your for loop define an Array that will hold all added markers. E.g. allMarkers = []

Inside of your for loop after creating the marker, push it in said Array. E.g. allMarkers.push(marker)

When you want to remove the first marker: allMarkers[0].setMap(null), or the third marker: allMarkers[2].setMap(null)




回答2:


Yes, this is possible. The Google Maps documentation covers this fully, including code examples, etc. Essentially markers are overlays rather than the map itself. You can put these overlays into an array and then use setMap() to null to hide.

Fully documentation here.



来源:https://stackoverflow.com/questions/13203323/remove-one-of-many-markers-on-google-maps-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!