传单-如何找到现有的标记,并删除标记?

时间:2021-12-23 22:07:49

I have started using leaflet as an open source map, http://leaflet.cloudmade.com/

我已经开始使用传单作为开放源码的地图,http://leaflet.cloudmade.com/。

The following jQuery code will enable the creation of markers on the map on map click:

以下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();
};

But there is currently no way for me (in my code) to delete existing markers, or find all the markers i've created on a map and put them into an array. Can anyone help me understand how to do this? Leaflet documentation is available here : http://leaflet.cloudmade.com/reference.html

但是目前我(在我的代码中)没有办法删除现有的标记,或者找到我在地图上创建的所有标记并将它们放入数组中。谁能帮我弄明白怎么做这件事吗?Leaflet文档可以在这里找到:http://leaflet.cloudmade.com/reference.html

8 个解决方案

#1


120  

you have to put your "var marker" out of the function. Then later you can access it :

必须将“var marker”从函数中删除。然后您可以访问它:

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

then later :

之后:

map.removeLayer(marker)

But you can only have the latest marker that way, because each time, the var marker is erased by the latest. So one way to go is to create a global array of marker, and you add your marker in the global array.

但是您只能使用最新的标记,因为每次,var标记都会被最新的删除。一种方法是创建一个全局标记数组,然后在全局数组中添加标记。

#2


42  

You can also push markers into an array. See code example, this works for me:

还可以将标记插入数组中。参见代码示例,这对我很有效:

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

#3


24  

Here is the code and demo for Adding the marker, deleting any of the marker and also getting all the present/added markers :

这是添加标记、删除任何标记以及获得所有当前/添加标记的代码和演示:

Here is the entire JSFiddle code . Also here is the full page demo.

这是整个JSFiddle代码。这里还有完整的页面演示。

Adding the marker :

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

Deleting the Marker :

// 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 in the map :

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

#4


14  

Here's a jsFiddle that lets you to create markers using your onMapClick method, then delete them by clicking a link.

下面是一个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.

这个过程类似于undefined's—将每个新标记添加到标记数组中,以便您可以在稍后与它交互时访问特定标记。

#5


7  

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

(1)添加层组和数组作为全局变量来保存层并引用层:

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

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

(2) add map

(2)添加地图

(3) Add group layer to map

(3)添加组层映射。

map.addLayer(search_group);

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.

(4) add to map函数,弹出一个包含链接的弹出窗口,点击后会有一个remove选项。这个链接的id为该点的lat长。然后将这个id与单击创建的标记并想要删除它时进行比较。

 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:

(5)删除功能,将标记lat long与删除中触发的id进行比较:

$(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);
            }

    }

    }  

#6


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

#7


0  

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!

在我的示例中,我有各种层组,以便用户可以显示/隐藏类似类型标记的集群。但是,在任何情况下,您都可以通过在层组上循环来查找和删除单个标记。在循环过程中,搜索带有自定义属性的标记(在我的例子中是“key”),在将标记添加到层组时添加该标记。添加“key”就像添加title属性一样。稍后会得到一个图层选项。当你找到匹配的时候,你。removelayer(),它就会去掉那个标记。希望这能帮到你!

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

#8


0  

Have you tried layerGroup yet?

你试过layerGroup吗?

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

文档在这里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)

#1


120  

you have to put your "var marker" out of the function. Then later you can access it :

必须将“var marker”从函数中删除。然后您可以访问它:

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

then later :

之后:

map.removeLayer(marker)

But you can only have the latest marker that way, because each time, the var marker is erased by the latest. So one way to go is to create a global array of marker, and you add your marker in the global array.

但是您只能使用最新的标记,因为每次,var标记都会被最新的删除。一种方法是创建一个全局标记数组,然后在全局数组中添加标记。

#2


42  

You can also push markers into an array. See code example, this works for me:

还可以将标记插入数组中。参见代码示例,这对我很有效:

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

#3


24  

Here is the code and demo for Adding the marker, deleting any of the marker and also getting all the present/added markers :

这是添加标记、删除任何标记以及获得所有当前/添加标记的代码和演示:

Here is the entire JSFiddle code . Also here is the full page demo.

这是整个JSFiddle代码。这里还有完整的页面演示。

Adding the marker :

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

Deleting the Marker :

// 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 in the map :

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

#4


14  

Here's a jsFiddle that lets you to create markers using your onMapClick method, then delete them by clicking a link.

下面是一个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.

这个过程类似于undefined's—将每个新标记添加到标记数组中,以便您可以在稍后与它交互时访问特定标记。

#5


7  

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

(1)添加层组和数组作为全局变量来保存层并引用层:

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

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

(2) add map

(2)添加地图

(3) Add group layer to map

(3)添加组层映射。

map.addLayer(search_group);

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.

(4) add to map函数,弹出一个包含链接的弹出窗口,点击后会有一个remove选项。这个链接的id为该点的lat长。然后将这个id与单击创建的标记并想要删除它时进行比较。

 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:

(5)删除功能,将标记lat long与删除中触发的id进行比较:

$(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);
            }

    }

    }  

#6


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

#7


0  

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!

在我的示例中,我有各种层组,以便用户可以显示/隐藏类似类型标记的集群。但是,在任何情况下,您都可以通过在层组上循环来查找和删除单个标记。在循环过程中,搜索带有自定义属性的标记(在我的例子中是“key”),在将标记添加到层组时添加该标记。添加“key”就像添加title属性一样。稍后会得到一个图层选项。当你找到匹配的时候,你。removelayer(),它就会去掉那个标记。希望这能帮到你!

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

#8


0  

Have you tried layerGroup yet?

你试过layerGroup吗?

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

文档在这里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)