【问题标题】:Remove /Hide Marker from search result after search is finished -Leaflet搜索完成后从搜索结果中删除/隐藏标记 - 传单
【发布时间】:2020-08-25 05:21:11
【问题描述】:

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

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

【问题讨论】:

  • 你能创建一个活的 jsfiddle

标签: javascript search leaflet geojson markers


【解决方案1】:

将您的标记保存到一个变量中,并在触发事件“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;
   }
});

【讨论】:

  • 感谢您的回答,但不知何故,上述答案不适用于我的代码。它仍然没有删除标记​​span>
  • 我将 ('search:collapsed') 更改为 ('search: cancel') 并且它有效。感谢@falke Design 的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多