program story

전단지-기존 마커를 찾고 마커를 삭제하는 방법은 무엇입니까?

inputbox 2020. 9. 13. 10:29
반응형

전단지-기존 마커를 찾고 마커를 삭제하는 방법은 무엇입니까?


저는 리플렛을 오픈 소스 맵으로 사용하기 시작했습니다. http://leaflet.cloudmade.com/

다음 jQuery 코드를 사용하면지도 클릭시지도에 마커를 만들 수 있습니다.

 map.on('click', onMapClick);
function onMapClick(e) {
        var marker = new L.Marker(e.latlng, {draggable:true});
        map.addLayer(marker);
        marker.bindPopup("<b>Hello world!</b><br />I am a popup.").openPopup();
};

그러나 현재는 (내 코드에서) 기존 마커를 삭제하거나지도에서 만든 모든 마커를 찾아 배열에 넣을 수있는 방법이 없습니다. 누구든지이 작업을 수행하는 방법을 이해하도록 도울 수 있습니까? 전단지 문서는 http://leaflet.cloudmade.com/reference.html에서 볼 수 있습니다.


함수에서 "var 마커"를 제거해야합니다. 그런 다음 나중에 액세스 할 수 있습니다.

var marker;
function onMapClick(e) {
        marker = new L.Marker(e.latlng, {draggable:true});
        map.addLayer(marker);
        marker.bindPopup("<b>Hello world!</b><br />I am a popup.").openPopup();
};

나중에 :

map.removeLayer(marker)

그러나 매번 var 마커가 최신 마커로 지워지기 때문에 최신 마커 만 가질 수 있습니다. 따라서 한 가지 방법은 마커의 전역 배열을 만들고 전역 배열에 마커를 추가하는 것입니다.


마커를 배열로 밀어 넣을 수도 있습니다. 코드 예제를 참조하십시오.

/*create array:*/
var marker = new Array();

/*Some Coordinates (here simulating somehow json string)*/
var items = [{"lat":"51.000","lon":"13.000"},{"lat":"52.000","lon":"13.010"},{"lat":"52.000","lon":"13.020"}];

/*pushing items into array each by each and then add markers*/
function itemWrap() {
for(i=0;i<items.length;i++){
    var LamMarker = new L.marker([items[i].lat, items[i].lon]);
    marker.push(LamMarker);
    map.addLayer(marker[i]);
    }
}

/*Going through these marker-items again removing them*/
function markerDelAgain() {
for(i=0;i<marker.length;i++) {
    map.removeLayer(marker[i]);
    }  
}

다음의 코드와 데모입니다 마커를 추가 , 마커 중 하나를 삭제 하고 또한 모든 본 추가 / 마커를 받고는 :

다음은 전체 JSFiddle 코드 입니다. 또한 여기에 전체 페이지 데모가 있습니다.

마커 추가 :

// Script for adding marker on map click
map.on('click', onMapClick);

function onMapClick(e) {

    var geojsonFeature = {

        "type": "Feature",
        "properties": {},
        "geometry": {
                "type": "Point",
                "coordinates": [e.latlng.lat, e.latlng.lng]
        }
    }

    var marker;

    L.geoJson(geojsonFeature, {

        pointToLayer: function(feature, latlng){

            marker = L.marker(e.latlng, {

                title: "Resource Location",
                alt: "Resource Location",
                riseOnHover: true,
                draggable: true,

            }).bindPopup("<input type='button' value='Delete this marker' class='marker-delete-button'/>");

            marker.on("popupopen", onPopupOpen);

            return marker;
        }
    }).addTo(map);
}

마커 삭제 :

// Function to handle delete as well as other events on marker popup open

function onPopupOpen() {

    var tempMarker = this;

    // To remove marker on click of delete button in the popup of marker
    $(".marker-delete-button:visible").click(function () {
        map.removeLayer(tempMarker);
    });
}

지도에서 모든 마커 가져 오기 :

// getting all the markers at once
function getAllMarkers() {

    var allMarkersObjArray = []; // for marker objects
    var allMarkersGeoJsonArray = []; // for readable geoJson markers

    $.each(map._layers, function (ml) {

        if (map._layers[ml].feature) {

            allMarkersObjArray.push(this)
            allMarkersGeoJsonArray.push(JSON.stringify(this.toGeoJSON()))
        }
    })

    console.log(allMarkersObjArray);
}

// any html element such as button, div to call the function()
$(".get-markers").on("click", getAllMarkers);

다음은 메소드를 사용하여 마커를 만든 다음 링크를 클릭하여 삭제할 있는 jsFiddle 입니다 onMapClick.

The process is similar to undefined's - add each new marker to a markers array so you can access a specific marker when you want to interact with it later.


(1) add layer group and array to hold layers and reference to layers as global variables:

var search_group = new L.LayerGroup(); var clickArr = new Array();

(2) add map

(3) Add group layer to map

map.addLayer(search_group);

(4) the add to map function, with a popup that contains a link, which when clicked will have a remove option. This link will have, as its id the lat long of the point. This id will then be compared to when you click on one of your created markers and you want to delete it.

 map.on('click', function(e) {
        var clickPositionMarker = L.marker([e.latlng.lat,e.latlng.lng],{icon: idMarker});
        clickArr.push(clickPositionMarker);
        mapLat = e.latlng.lat;
        mapLon = e.latlng.lng;
        clickPositionMarker.addTo(search_group).bindPopup("<a name='removeClickM' id="+e.latlng.lat+"_"+e.latlng.lng+">Remove Me</a>")
                .openPopup();   

                /*   clickPositionMarker.on('click', function(e) {
                  markerDelAgain(); 
                }); */


});

(5) The remove function, compare the marker lat long to the id fired in the remove:

$(document).on("click","a[name='removeClickM']", function (e) {

      // Stop form from submitting normally
    e.preventDefault();

    for(i=0;i<clickArr.length;i++) {

    if(search_group.hasLayer(clickArr[i]))
    {
        if(clickArr[i]._latlng.lat+"_"+clickArr[i]._latlng.lng==$(this).attr('id'))
            {
                hideLayer(search_group,clickArr[i]);
                clickArr.splice(clickArr.indexOf(clickArr[i]), 1);
            }

    }

    }  

When you save the reverence to the marker in the adding function the marker can remove it self. No need for arrays.

function addPump(){
   var pump = L.marker(cords,{icon: truckPump}).addTo(map).bindPopup($('<a href="#" class="speciallink">Remove ME</a>').click(function() {
            map.removeLayer(pump);
          })[0]);
        }

Have you tried layerGroup yet?

Docs here https://leafletjs.com/reference-1.2.0.html#layergroup

Just create a layer, add all marker to this layer, then you can find and destroy marker easily.

var markers = L.layerGroup()
const marker = L.marker([], {})
markers.addLayer(marker)

In my case, I have various layer groups so that users can show/hide clusters of like type markers. But, in any case you delete an individual marker by looping over your layer groups to find and delete it. While looping, search for a marker with a custom attribute, in my case a 'key', added when the marker was added to the layer group. Add your 'key' just like adding a title attribute. Later this is gotten an a layer option. When you find that match, you .removeLayer() and it gets rid of that particular marker. Hope that helps you out!

eventsLayerGroup.addLayer(L.marker([tag.latitude, tag.longitude],{title:tag.title, layer:tag.layer, timestamp:tag.timestamp, key:tag.key, bounceOnAdd: true, icon: L.AwesomeMarkers.icon({icon: 'vignette', markerColor: 'blue', prefix: '', iconColor: 'white'}) }).bindPopup(customPopup(tag),customOptions).on('click', markerClick)); 

function removeMarker(id){
    var layerGroupsArray = [eventsLayerGroup,landmarksLayerGroup,travelerLayerGroup,marketplaceLayerGroup,myLayerGroup];
    $.each(layerGroupsArray, function (key, value) {
        value.eachLayer(function (layer) {
            if(typeof value !== "undefined"){
                if (layer.options.layer){
                    console.log(layer.options.key);
                    console.log(id);
                    if (id === layer.options.key){
                        value.removeLayer(layer);
                    }
                }
            }
        });
    });
}

참고URL : https://stackoverflow.com/questions/9912145/leaflet-how-to-find-existing-markers-and-delete-markers

반응형