这是添加标记,删除任何标记以及获取所有当前/添加标记的代码和演示。:
这是整个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);