简体   繁体   English

单击选项时如何从谷歌地图 api 中删除标记

[英]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.我有 3 个带有按钮的独立地图,例如餐厅、酒吧、咖啡馆等。当我单击一个选项时,标记会显示在 map 上,但当我单击下一个选项时,旧标记仍保留在那里。

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: 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: 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-->

You are missing markers.push(marker);你缺少markers.push(marker); in your createMarker function.在您的createMarker function 中。 That keeps references to the markers that are added to the map, so they can be removed later by the clearMarkers function.这保留了对添加到 map 的标记的引用,因此它们可以稍后被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-->

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM