2013-08-29 2 views
8

지도에 Leaflet.js를 사용하고 있습니다. 이제지도에서 추가 된 레이어를 제거하고 싶습니다. 입력 # 버튼을 클릭하면 체크 된 모든 체크 박스가 체크되지 않은 상태로 변경되고 모든 해당 레이어가 맵에서 제거됩니다.Leaflet.js :지도에서 여러 레이어를 제거하는 방법

지도에서 레이어를 제거하려면 레이어의 ID가 필요합니다. 이 id는 해당 확인란의 id와 같습니다. 그래서 jQuery를 사용하여 체크 된 모든 체크 박스의 ID를 가져 와서 객체에 값을 저장합니다. 여기에는 someObj.idsChecked이라는 값이 있습니다.

나는 그것이 을 console.log 표시하면서 원하는 값을 작동하지 않는 하나 개의 층을 제거하기 위해 저장된 값 를 사용하려고하면. 여기 예 : mapcat52.

map.removeLayer (mapcat52)과 같이 함수에 하드 코딩 된 이전 ID를 삽입하는 동안 예상대로 작동합니다.

내 코드 또는 내 생각에 오류가 어디 있습니까?
도움을 주시면 감사하겠습니다.

html로

<input type="button" id="selectnone" value="deselect all" /> 

<!-- checkboxes --> 
<input id="mapcat52" type="checkbox" name="maplayer" class="maplayer"> 
<label for="mapcat52">Map Layer One</label> 

<input id="mapcat53" type="checkbox" name="maplayer" class="maplayer"> 
<label for="mapcat53">Map Layer Two</label> 

... 

JS :

$('#selectnone').click(function() { 
    var someObj = {}; 
    someObj.idsChecked = []; 

    $("input:checkbox").each(function() { 
     if ($(this).is(":checked")) { 

      someObj.idsChecked.push($(this).attr("id")); 
     } 
    }).attr('checked', false); 

    $.each(someObj.idsChecked,function(id, val) { 

      // displays the wanted value, e.g. "mapcat52" if checkbox with this id is checked 
      console.log(val); 

      // does not work: inserted value 
      map.removeLayer(val); 

      // works: hard coded value of the leaflet.js/input id 
      map.removeLayer(mapcat52); 
     }); 

}); 
+0

을 선택하면 : https://stackoverflow.com/questions/39186001/ 방법에 가까운 모든 팝업 –

답변

6

전단지 API의 문서 http://leafletjs.com/reference.html#map-removelayer에 따르면, removeLayer는 i 레이어 매개 변수를 취합니다 removeLayer(<ILayer> layer)을하지만 당신은 그것을 문자열 전달되고 있습니다 $(this).attr("id")

변수에 layer 객체가 이미있는 것처럼 보입니다 : mapcat52. 당신은 removeLayer에 전달할 당신이 그들을 만들 때 다음 레이어의 객체를 저장 ID로 그들을 볼 수 있었다 :

var layers = new Array(); 

// create layer 
var mapcat52 = new MyCustomLayer(latlng); 

// save to layers list 
layers["mapcat52"] = mapcat52; 
... 

// remove layers 
$.each(someObj.idsChecked, function(id, val) { 
    // look up layer object by id 
    var layerObj = layers[val]; 
    // remove layer 
    map.removeLayer(layerObj); 
}); 
+0

제안을 주셔서 대단히 감사드립니다. 이것은 내 경우에 맞는 것 같습니다. 나는 곧 그것을 시도 할 것이다. – LuNarez

16

내가 가장 쉬운 방법/제거 맵을 사용하는 것입니다에서 (토글) 레이어를 추가하는 말을 a LayerGroup.

지도에 개별 레이어를 추가하기 전에 대신 레이어 그룹에 추가 한 다음 해당 레이어 그룹을지도에 추가하십시오.

그러면 레이어를 제거해야 할 때 clearLayers() 함수를 호출하기 만하면됩니다. LayerGroup http://leafletjs.com/reference.html#layergroup

의 API 밖으로

확인 예

var map = L.map('leafletMap', {minZoom:11}).setView([37.8, -96], 11); 
var assetLayerGroup = new L.LayerGroup(); 
var marker1 = L.marker([39.61, -105.02]).bindPopup('This is Littleton, CO.'); 
var marker2 = L.marker([39.74, -104.99]).bindPopup('This is Denver, CO.'), 
assetLayerGroup.addLayer(marker1); 
assetLayerGroup.addLayer(marker2); 

제거 확인란이 도움이 될

assetLayerGroup.clearLayers(); 
+0

깨끗하고 명확한 예를 들어 주셔서 감사합니다. 그래서 그 중 하나를 찾기 힘들어! – jmadsen

관련 문제