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

问题描述

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

//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;
   }
});

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...