Configuré el localizador de tiendas usando Google Map JavaScript Api. cuando alguien ingrese su ubicación, encontrará las tiendas dentro de un radio de 50 km. Quiero que cuando el usuario busque por segunda vez, se elimine el marcador anterior (primera búsqueda). He agregado 4 ubicaciones (localizadores de tiendas) en el mapa de Google.
CÓDIGO JS:
if(myCity.getBounds().contains( new google.maps.LatLng( location1 ) ) ){ var location1_marker = new google.maps.Marker({ title:'sleep dallas', position: location1, map: map, icon: { labelOrigin: new google.maps.Point(40, 80), url: 'css/marker-2.png', size: new google.maps.Size(80, 80), }, }); }else if ( myCity.getBounds().contains( new google.maps.LatLng( location2 ) ) ) { var location2_marker = new google.maps.Marker({ position: location2, map: map, icon: { labelOrigin: new google.maps.Point(40, 80), url: 'css/marker-2.png', size: new google.maps.Size(80, 80), }, }); }else if ( myCity.getBounds().contains( new google.maps.LatLng( location3 ) ) ) { var location3_marker = new google.maps.Marker({ title:'sleep better', position: location3, map: map, icon: { labelOrigin: new google.maps.Point(40, 80), url: 'css/marker-2.png', size: new google.maps.Size(80, 80), }, }); }else if ( myCity.getBounds().contains( new google.maps.LatLng( location4 ) ) ) { var location4_marker = new google.maps.Marker({ title:'sleep better', position: location4, map: map, icon: { labelOrigin: new google.maps.Point(40, 80), url: 'css/marker-2.png', size: new google.maps.Size(80, 80), }, }); }else{ alert('There is no any clinic around the radius of 50km in your location...!'); }// Intenta ocultar otros marcadores pero falló, aquí necesito ayuda
if(location1_marker.getMap()){ location2_marker.setMap(null) location3_marker.setMap(null) location4_marker.setMap(null) }else if(location2_marker.getMap()){ location1_marker.setMap(null) location3_marker.setMap(null) location4_marker.setMap(null) }else if(location3_marker.getMap()){ location1_marker.setMap(null) location2_marker.setMap(null) location4_marker.setMap(null) }else if(location4_marker.getMap()){ location1_marker.setMap(null) location2_marker.setMap(null) location3_marker.setMap(null) }else{ alert('Nothing happend'); }Preferiría sugerirle que use una lista de marcadores.
Cuando inserta un nuevo marcador en la lista, puede verificar la longitud de la lista y, si supera cierto umbral, puede configurarlo como null y luego eliminarlo de la lista.
Como ejemplo:
const THRESHOLD = 3 // up to 3 active markers let list = [] // list of markers const onAddMarker = marker => { // init marker let marker = new google.maps.Marker([...opts]) // push marker to list list.push(marker) // check list length and remove oldest marker (if needed) if (list.length > THRESHOLD) list.shift().setMap(null) }