简体   繁体   English

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

[英]Remove /Hide Marker from search result after search is finished -Leaflet

In my current code, I am able to search and display a marker on the search location but when I remove text from the search bar or close search bar marker is still visible on map .until I refresh the page I can visualize the search result marker on the map.在我当前的代码中,我能够在搜索位置搜索和显示标记,但是当我从搜索栏中删除文本或关闭搜索栏标记时,地图上仍然可见。直到我刷新页面,我才能可视化搜索结果标记在地图上。 how can I hide or remove the search result marker from the map once I close the search bar or remove text from the search bar?关闭搜索栏或从搜索栏中删除文本后,如何从地图中隐藏或删除搜索结果标记?

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

Save your marker to a variable and remove it after the event 'search:collapsed' is fired:将您的标记保存到一个变量中,并在事件 '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;
   }
});

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

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