搜索完成后,从搜索结果中删除/隐藏标记-传单

问题描述

在当前代码中,我能够搜索并在搜索位置上显示标记,但是当我从搜索栏中删除文字关闭搜索栏时,标记仍在地图上可见。直到刷新页面,我才能看到地图上的搜索结果标记关闭搜索栏或从搜索栏中删除文本后,如何在地图上隐藏或删除搜索结果标记

//add Search Control so load the Geojson of point of interest
    var featuresLayer = new L.GeoJSON(data);
  
    var Icon = L.icon({
            iconUrl: 'icon-red.png',iconSize:     [25,41],// size of the icon
            iconAnchor:   [13,38],// point of the icon which will correspond to marker's location
            popupAnchor:  [1,-34],// point from which the popup should open relative to the iconAnchor
            shadowSize: [41,41] // shadow casting of icon
    });
    
    var searchControl = new L.Control.Search({
        layer: featuresLayer,propertyName: 'name',autoCollapse: false,collapsed:false,autoType: false,position:'topright',movetoLocation: function(latlng,title,map) {
            map.setView(latlng,17); // access the zoom
            console.log(latlng);
            L.marker(latlng,{icon: Icon}).addTo(map).bindPopup('<h4>'+ latlng.layer.feature.properties.name +'</h4>').openPopup();
            },});
    
    //inizialize search control
    map.addControl(searchControl);     

解决方法

将标记保存到变量中,并在触发“ search:collapsed”事件后将其删除:

var searchMarker = null;
var searchControl = new L.Control.Search({
        layer: featuresLayer,propertyName: 'name',autoCollapse: false,collapsed:false,autoType: false,position:'topright',moveToLocation: function(latlng,title,map) {
            map.setView(latlng,17); // access the zoom
            console.log(latlng);
            searchMarker = L.marker(latlng,{icon: Icon}).addTo(map).bindPopup('<h4>'+ latlng.layer.feature.properties.name +'</h4>').openPopup();
            },});

searchControl.on('search:cancel',()=>{
   if(searchMarker && map.hasLayer(searchMarker)){
       searchMarker.removeFrom(map);
       searchMarker = null;
   }
});