Add up to 4 markers on map click
by Sebastian Kay
HTML
<link href="https://cdn.jsdelivr.net/npm/leaflet@1/dist/leaflet.css" type="text/css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/leaflet@1/dist/leaflet-src.js"></script>
<div id="map"></div>
CSS
html,
body {
margin: 0;
padding: 0;
height: 100vh;
max-height: 100vh;
}
#map {
width: 100%;
height: 100vh;
}
JavaScript
const MARKERS_MAX = 2
const jsonData = {
"extraction_exit_names": [
"Dead Man's Place",
"Boat",
"Scav House",
"UN Roadblock"
],
"extraction_transit_names": [
"Transit to Factory",
"Transit to Reserve",
"Transit to Lighthouse"
],
"remaining_time": 29
}
const data = jsonData;
console.log(data["extraction_transit_names"])
const map = L.map("map").setView([51.4661, 7.2491], 14)
L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
attribution:
'© <a href="https://openstreetmap.org/copyright">OpenStreetMap</a> contributors',
}).addTo(map)
// a layer group, used here like a container for markers
const markersGroup = L.layerGroup()
map.addLayer(markersGroup)
// Erstelle ein neues Control-Element
const customControl = L.Control.extend({
onAdd: function (map) {
this.container = L.DomUtil.create("div", "custom-control")
//this.container.innerHTML = '<h2>Add Marker to Pos: </h2>';
return this.container
},
updateText: function (latlng) {
if (this.container) {
this.container.innerHTML = `<h2>Add Marker to Pos: ${latlng.toString()}</h2>`
}
},
clearText: function () {
if (this.container) {
this.container.innerHTML = ""
}
},
onRemove: function (map) {
// Nichts zu tun hier
},
})
// Füge das Control-Element zur Karte hinzu und speichere die Referenz
const myControl = new customControl({ position: "topright" })
map.addControl(myControl)
map.on("click", function (e) {
// get the count of currently displayed markers
const markersCount = markersGroup.getLayers().length
if (markersCount < MARKERS_MAX) {
const marker = L.marker(e.latlng).addTo(markersGroup)
console.log("Add Marker to Pos: " + e.latlng)
// Aktualisiere den Text des Control-Elements
myControl.updateText(e.latlng)
// Entferne das Control-Element nach 3 Sekunden
setTimeout(function () {
myControl.clearText()
}, 3000)
return
}
// remove the...