How to remove Markers one by one (javascript)

1

I have the following code to add my markers:

 function setParking(map)
{
   var pointA = { lat: -16.113700, lng: -45.825545 };
   var pointB = { lat: -15.284216, lng: -44.658747 };
   var poinC = { lat: -16.139567, lng: -43.236152 };
   
   setMap(map, pointA);
   setMap(map, pointB);
   setMap(map, poinC);
}

function setParkingMap(map, point)
        {
                var contentString = '<div id="content">'+
                    '<div id="siteNotice">'+
                    '</div>'+
                    '<h1 id="firstHeading" class="firstHeading">Loja Cascais</h1>' +
                    '<div id="bodyContent">'+
                    '<p><b>Morada:</b> Teste' +
                    '<p><b>Horário:</b> Teste 2 ' +
                    '</div>' +
                    '<button onclick="">Obter indicações</button>'
                '</div>';

                var infowindow = new google.maps.InfoWindow({
                    content: contentString
                });

                var marker = new google.maps.Marker({
                    position: point,
                    map: map,
                    title: 'Teste'
                });
                marker.addListener('click', function() {
                    infowindow.open(map, marker);
                });
        }

function initMap() {
var mapOptions = {
            zoom: 15, center: new google.maps.LatLng(38.696029, -9.424029)
        }

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

setParking(map)
}

  jQuery(document).ready(function () {
        initMap();
    });

What I want now is when I click on the checkbox to call a function that deletes a marker or more, I have tried the following:

poinC.setMap(null) , but it does not.

Does anyone know how I can do this?

    
asked by anonymous 20.05.2016 / 13:09

2 answers

1

I already discovered what was wrong, I was erasing points and not markers, I created markers= [] , whenever I add a marker I do markers.push(marker); and the delete function do:

for (var i = 0; i < markers.length; i++) { 
  markers[i].setMap(map); 
}
    
20.05.2016 / 13:46
1

If you can suggest a way to avoid the for loop, you can do:

<input id="chkOranTarif" type="checkbox" name="chkOranTarif" class="psform__checkbox" onchange="removeMap(this)" data-marker="<MARKER A REMOVER>"/>

EX:

<input id="chkOranTarif" type="checkbox" name="chkOranTarif" class="psform__checkbox" onchange="removeMap(this);" data-marker="0"/>

...

function removeMap(checkbox) {
   var markerToDel = checkbox.data('marker'); // aqui vai ser o num 0
   markers[markerToDel].setMap(null); // apagar o primeiro, markers[0].setMap(null);
}
    
20.05.2016 / 14:02