-1

I'm a bit stuck on how I could remove the old markers from the google map

The issue is this, using the setMap function, it removes the markers but I want it to only remove the old one and not the new one.

function dataMarkerMapForm(){
    
    var latitud = parseFloat($("#latitud").val());
    var longitud = parseFloat($("#longitud").val());
    
    var coordinates = { lat : latitud, lng : longitud };
    
    createMapModal(coordinates);
    
}

function createMapModal(coordinates){

    var map = new google.maps.Map(document.getElementById('modalBodyMap'), {zoom: 16, center: coordinates});
     var marker = new google.maps.Marker({position: coordinates, map: map});
     
     
     
     const infowindow = new google.maps.InfoWindow();
    const geocoder = new google.maps.Geocoder();

    map.addListener("click", (mapsMouseEvent) => {
        marker.setMap(null);


        var coordinates = { lat :mapsMouseEvent.latLng.lat(), lng : mapsMouseEvent.latLng.lng() };

        var markergeo = new google.maps.Marker({position: coordinates, map: map});



geocoder.geocode({ location: mapsMouseEvent.latLng }, (results, status) => {

    if (status === "OK") {
    if (results[0]) {

      infowindow.setContent(results[0].formatted_address);

      formDatos(results[0]);
     // markergeo.setMap(null);

      infowindow.open(map, markergeo);

    } else {
      window.alert("No results found");
    }
  } else {
    window.alert("Geocoder failed due to: " + status);
  }
}); 
 
          
});


  

    $("#modalMap").modal("open")
    
    //  $("#modalBodyMap").css("position","fixed !important");
}

I have two types of markers one the one that shows it when starting the map and the other in which the user clicks on a certain position on the map

I want to delete that one in which when the user clicks on a certain part of the map, the old one is deleted and the new one is preserved.

I hope you have made me understand, I share photos just in case.

Tried with the geo marker, but it clears all the markers and I want to keep the new one ejemplo1 ejemplo2

geocodezip
  • 158,664
  • 13
  • 220
  • 245
ZeroMF
  • 3
  • 3

1 Answers1

0

You should add a global variable to have the value of the marker. Then when you call the createMapModal function you should check if this global variable has a value and not defined, then you should call setMap(null) like that

 if (marker) {
            marker.setMap(null);
        }

setMap Renders the marker on the specified map or panorama. If the map is set to null, the marker will be removed.

so after that, you can add a new marker and assign it to the global variable you have like that

marker = new google.maps.Marker({
            position,
            map:map,
            draggable: true,
            clickable: true,
            // icon: 'assets/images/favicon.png',
        });
        marker.setVisible(true);

Amr Omar
  • 399
  • 5
  • 12