Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
90 views
in Technique[技术] by (71.8m points)

javascript - How to remove markers from google maps api when an option is clicked

I am building a travel website for a course that I am doing.

I have 3 separate maps with buttons eg restaurants, bars, cafes etc. I have it that the markers show up on the map when I click on an option but when I click on the next option the old markers remain there.

I would like the old markers to be removed and replaced with the new markers.

How do I remove the old markers when adding new ones?

javascript:

var map1, map2, map3;
var markers = [];


function initMap() {
    let mapOptions = {
        zoom: 13,
    }
    mapOptions.center = new google.maps.LatLng(21.038598, 105.830440); // hanoi
    map1 = new google.maps.Map(document.getElementById("map-hanoi"), mapOptions);
    mapOptions.center = new google.maps.LatLng(22.336459, 103.843878); // sapa
    map2 = new google.maps.Map(document.getElementById("map-sapa"), mapOptions);
    mapOptions.center = new google.maps.LatLng(15.880314, 108.339319); // hoi-an
    map2 = new google.maps.Map(document.getElementById("map-hoi-an"), mapOptions);
}
function displayLocationsOfType(mapInstance, locationTypes) {
     var request = {
        location: mapInstance.getCenter(),
        radius: 8047,
        types: locationTypes
      }
    var service = new google.maps.places.PlacesService(mapInstance);
    service.nearbySearch(request, callback);
}
function callback(results, status) {
  if (status == google.maps.places.PlacesServiceStatus.OK) {
    clearMarkers();
    console.log(results.length);
    for (var i = 0; i < results.length; i++) {
      createMarker(results[i]);
    }
  }
}
function createMarker(place) {
    
  var placeLoc = place.geometry.location;
  var marker = new google.maps.Marker({
    map: map1,
    position: place.geometry.location,
    title: place.name
  })
}

function clearMarkers() {
    for (var i = 0; i < markers.length; i++) {
        if (markers[i]) {
            markers[i].setMap(null);
        }
    }
    markers = [];
}

function getMapInstanceFromPlaceNameIdentifier(placeNamesIdentifier) {
    if(placeNamesIdentifier === 'hanoi') {
        return map1;
    } else if(placeNamesIdentifier === 'sapa') {
        return map2;
    } else if(placeNamesIdentifier === 'hoi-an') {
        return map3;
    }
    return null;
}


const placeNamesIdentifiers = ['hanoi', 'sapa', 'hoi-an'];
placeNamesIdentifiers.forEach((eachPlaceIdentifier) => {
 $("#" + eachPlaceIdentifier + "-bars").click(function(){
        clearMarkers();
        const mapInstance = getMapInstanceFromPlaceNameIdentifier(eachPlaceIdentifier);
        displayLocationsOfType(mapInstance, ['bar']);
  });
   $("#" + eachPlaceIdentifier + "-restaurants").click(function(){
       clearMarkers();
        const mapInstance = getMapInstanceFromPlaceNameIdentifier(eachPlaceIdentifier);
        displayLocationsOfType(mapInstance, ['restaurant']);
  });
     $("#" + eachPlaceIdentifier + "-cafes").click(function(){
         clearMarkers();
        const mapInstance = getMapInstanceFromPlaceNameIdentifier(eachPlaceIdentifier);
        displayLocationsOfType(mapInstance, ['cafe']);
  });
     $("#" + eachPlaceIdentifier + "-hotels").click(function(){
         clearMarkers();
        const mapInstance = getMapInstanceFromPlaceNameIdentifier(eachPlaceIdentifier);
        displayLocationsOfType(mapInstance, ['lodging']);
  });
     $("#" + eachPlaceIdentifier + "-attractions").click(function(){
         clearMarkers();
        const mapInstance = getMapInstanceFromPlaceNameIdentifier(eachPlaceIdentifier);
        displayLocationsOfType(mapInstance, ['tourist_attraction']);
  });
});

html:

 <section class="choices row no-gutters" id="choices-hanoi">
                    <div class="col-md-2 col-4 grow">
                        <a href="#choices-hanoi" class="choices-items" id="hanoi-bars">
                            <i class="fas fa-cocktail icon"></i>
                            <h4>Bars</h4>
                        </a>
                    </div>

                    <div class="col-md-2 col-4 grow">
                        <a href="#choices-hanoi" class="choices-items" id="hanoi-restaurants">
                            <i class="fas fa-utensils icon"></i>
                            <h4>Restaurants</h4>
                        </a>
                    </div>

                    <div class="col-md-2 col-4 grow">
                        <a href="#choices-hanoi" class="choices-items" id="hanoi-cafes">
                            <i class="fas fa-coffee icon"></i>
                            <h4>Cafes</h4>
                        </a>
                    </div>

                    <div class="col-md-2 col-4 grow">
                        <a href="#choices-hanoi" class="choices-items" id="hanoi-hotels">
                            <i class="fas fa-hotel icon"></i>
                            <h4>Hotels</h4>
                        </a>
                    </div>

                    <div class="col-md-2 col-4 grow">
                        <a href="#choices-hanoi" class="choices-items" id="hanoi-attractions">
                            <i class="fas fa-theater-masks icon"></i>
                            <h4>Attractions</h4>
                        </a>
                    </div>
                </section>
                <!--End of Hanoi Choices-->

                <!--Start of Hanoi Map-->
                <div class="map-container">
                    <div id="map-hanoi" class="maps"></div>
                </div>
                <!--End of Hanoi Map-->
question from:https://stackoverflow.com/questions/65864431/how-to-remove-markers-from-google-maps-api-when-an-option-is-clicked

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are missing markers.push(marker); in your createMarker function. That keeps references to the markers that are added to the map, so they can be removed later by the clearMarkers function.

function createMarker(place) {
  var placeLoc = place.geometry.location;
  var marker = new google.maps.Marker({
    map: map1,
    position: place.geometry.location,
    title: place.name
  })
  markers.push(marker);  // <---------------------------- here -------
}

working code snippet:

var map1, map2, map3;
var markers = [];


function initMap() {
  let mapOptions = {
    zoom: 13,
  }
  mapOptions.center = new google.maps.LatLng(21.038598, 105.830440); // hanoi
  map1 = new google.maps.Map(document.getElementById("map-hanoi"), mapOptions);
  mapOptions.center = new google.maps.LatLng(22.336459, 103.843878); // sapa
  map2 = new google.maps.Map(document.getElementById("map-sapa"), mapOptions);
  mapOptions.center = new google.maps.LatLng(15.880314, 108.339319); // hoi-an
  map2 = new google.maps.Map(document.getElementById("map-hoi-an"), mapOptions);
}

function displayLocationsOfType(mapInstance, locationTypes) {
  var request = {
    location: mapInstance.getCenter(),
    radius: 8047,
    types: locationTypes
  }
  var service = new google.maps.places.PlacesService(mapInstance);
  service.nearbySearch(request, callback);
}

function callback(results, status) {
  if (status == google.maps.places.PlacesServiceStatus.OK) {
    clearMarkers();
    console.log(results.length);
    for (var i = 0; i < results.length; i++) {
      createMarker(results[i]);
    }
  }
}

function createMarker(place) {
  var placeLoc = place.geometry.location;
  var marker = new google.maps.Marker({
    map: map1,
    position: place.geometry.location,
    title: place.name
  })
  markers.push(marker);
}

function clearMarkers() {
  for (var i = 0; i < markers.length; i++) {
    if (markers[i]) {
      markers[i].setMap(null);
    }
  }
  markers = [];
}

function getMapInstanceFromPlaceNameIdentifier(placeNamesIdentifier) {
  if (placeNamesIdentifier === 'hanoi') {
    return map1;
  } else if (placeNamesIdentifier === 'sapa') {
    return map2;
  } else if (placeNamesIdentifier === 'hoi-an') {
    return map3;
  }
  return null;
}


const placeNamesIdentifiers = ['hanoi', 'sapa', 'hoi-an'];
placeNamesIdentifiers.forEach((eachPlaceIdentifier) => {
  $("#" + eachPlaceIdentifier + "-bars").click(function() {
    clearMarkers();
    const mapInstance = getMapInstanceFromPlaceNameIdentifier(eachPlaceIdentifier);
    displayLocationsOfType(mapInstance, ['bar']);
  });
  $("#" + eachPlaceIdentifier + "-restaurants").click(function() {
    clearMarkers();
    const mapInstance = getMapInstanceFromPlaceNameIdentifier(eachPlaceIdentifier);
    displayLocationsOfType(mapInstance, ['restaurant']);
  });
  $("#" + eachPlaceIdentifier + "-cafes").click(function() {
    clearMarkers();
    const mapInstance = getMapInstanceFromPlaceNameIdentifier(eachPlaceIdentifier);
    displayLocationsOfType(mapInstance, ['cafe']);
  });
  $("#" + eachPlaceIdentifier + "-hotels").click(function() {
    clearMarkers();
    const mapInstance = getMapInstanceFromPlaceNameIdentifier(eachPlaceIdentifier);
    displayLocationsOfType(mapInstance, ['lodging']);
  });
  $("#" + eachPlaceIdentifier + "-attractions").click(function() {
    clearMarkers();
    const mapInstance = getMapInstanceFromPlaceNameIdentifier(eachPlaceIdentifier);
    displayLocationsOfType(mapInstance, ['tourist_attraction']);
  });
});
html,
body,
.map-container {
  height: 100%;
  width: 100%;
  padding: 0;
  margin: 0;
}

.maps {
  height: 50%;
  width: 99%;
  border: solid blue 1px;
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=places&v=weekly" defer></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="choices row no-gutters" id="choices-hanoi">
  <div class="col-md-2 col-4 grow">
    <a href="#choices-hanoi" class="choices-items" id="hanoi-bars">
      <i class="fas fa-cocktail icon"></i>
      <h4>Bars</h4>
    </a>
  </div>

  <div class="col-md-2 col-4 grow">
    <a href="#choices-hanoi" class="choices-items" id="hanoi-restaurants">
      <i class="fas fa-utensils icon"></i>
      <h4>Restaurants</h4>
    </a>
  </div>

  <div class="col-md-2 col-4 grow">
    <a href="#choices-hanoi" class="choices-items" id="hanoi-cafes">
      <i class="fas fa-coffee icon"></i>
      <h4>Cafes</h4>
    </a>
  </div>

  <div class="col-md-2 col-4 grow">
    <a href="#choices-hanoi" class="choices-items" id="hanoi-hotels">
      <i class="fas fa-hotel icon"></i>
      <h4>Hotels</h4>
    </a>
  </div>

  <div class="col-md-2 col-4 grow">
    <a href="#choices-hanoi" class="choices-items" id="hanoi-attractions">
      <i class="fas fa-theater-masks icon"></i>
      <h4>Attractions</h4>
    </a>
  </div>
</section>
<!--End of Hanoi Choices-->

<!--Start of Hanoi Map-->
<div class="map-container">
  <div id="map-hanoi" class="maps"></div>
  <div id="map-sapa" class="maps" style="display:none"></div>
  <div id="map-hoi-an" class="maps" style="display:none"></div>
</div>
<!--End of Hanoi Map-->

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...