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

我已经开始使用传单作为一个开源的地图,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

219316 次浏览

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

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

当您在添加函数中保存对标记的尊敬时,标记可以自行删除它。不需要数组。

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

下面的 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)加入地图

(3) Add group layer to map

map.addLayer(search_group);

(4)添加到地图功能,弹出一个包含链接,当点击将有一个删除选项。这个链接将具有,因为它的 id 是点的末尾长度。然后,这个 id 将与您单击创建的标记之一并希望删除它时的 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)删除函数,将最后一个标记与删除中激发的 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);
}


}


}

下面是 添加记号笔删除任何标记获取所有当前/添加的标记的代码和演示:

这里是整个 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);

在我的例子中,我有各种各样的层组,这样用户就可以显示/隐藏类似类型标记的集群。但是,在任何情况下,您删除一个单独的标记,通过循环遍历您的层组,以查找和删除它。循环时,搜索一个带有自定义属性的标记,在我的例子中是一个“键”,当标记添加到层组时添加。添加“ 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);
}
}
}
});
});
}

你试过 layerGroup了吗?

我是医生

只要创建一个层,添加所有的标记到这个层,然后你就可以很容易地找到和消灭标记。

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

我所做的删除标记是这样创建一个按钮,谁允许我这样做

希望我能帮到某人:)

//Button who active deleteBool
const button = document.getElementById('btn')


//Boolean who let me delete marker
let deleteBool = false


//Button function to enable boolean
button.addEventListener('click',()=>{
deleteBool = true
})


// Function to delete marker
const deleteMarker = (e) => {
if (deleteBool) {
e.target.removeFrom(map)
deleteBooly = false
}
}


//Initiate map
var map = L.map('map').setView([51.505, -0.09], 13);


//Create one marker
let marker = L.marker([51.5, -0.09]).addTo(map)
//Add Marker Function
marker.on('click', deleteMarker)
body {
display: flex;
flex-direction: column;
}


#map{
width: 500px;
height: 500px;
margin: auto;
}


#btn{
width: 50px;
height: 50px;
margin: 2em auto;
}
<!DOCTYPE html>
<html lang="en">


<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="style.css" />
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A==" crossorigin="" />
<title>MovieCenter</title>
</head>


<body>
<div id="map"></div>
<button id="btn">Click me!</button>
<script script="script" src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js" integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA==" crossorigin=""></script>
<script src="script.js"></script>
</body>


</html>

如果您使用的是 L.Routing.control,那么包含在数组中保存标记的答案将不起作用。他们不为我工作。我发现 L.Routing.control 会自动添加标记,而删除标记则通过删除 L.Routing.control 来完成:

this.map.removeControl(this.routingControl)

路线被删除,所有的路标点/标记,除了第一个,当我 console. 日志的图层,图层与路标点仍然在那里,我想知道为什么。

这个解决方案最终对我奏效了:

this.map.eachLayer((layer: any) => {
if (layer.options.waypoints && layer.options.waypoints.length) {
this.map.removeLayer(layer);
}
});

如果将标记添加到层组,则可以将 removeLayer方法应用于层组 您需要在函数之外定义标记变量,以便能够删除它

var marker;
function newMarker() {
markerLayer = L.layerGroup();
marker = new L.marker( [12, 13],
{icon:greenMarker, clickable:true}).bindPopup("Hello Marker").addTo(markerLayer);


markerLayer.removeLayer(marker);
};