I would like to add and remove Markers in my Leaflet Map. i found this good topic but the code is in JS.
Leaflet - How to find existing markers, and delete markers?
My code is like that :
<template>
<l-map :zoom="zoom" :center="center">
<l-tile-layer :url="url" :attribution="attribution"></l-tile-layer>
<l-marker :lat-lng="marker" :draggable=true></l-marker>
</l-map>
</template>
<script>
data:function() {
return {
zoom:7,
center: L.latLng(33.901445, -5.532788),
url:'http://{s}.tile.osm.org/{z}/{x}/{y}.png',
attribution:'© <a href="http://osm.org/copyright">OpenStreetMap</a>
contributors',
marker: L.latLng(47.413220, -1.219482),
}},
</script>
Maybe i should start by creating a function on click like that :
<l-map :zoom="zoom" :center="center" v-on:click="addMarker"></l-map>
And then i wrtie the correct addMarker Function in method. But i can't find the right doc for that.
I would like also to get the position of the new Marker in Data..
Thank you
It turns out to be really, really easy. Use an array with v-for
instead of a single marker. Click on marker splices out the marker at that index. Click on map creates a new marker with the latlng. The snippet below is based on this fiddle.
var {
LMap,
LTileLayer,
LMarker
} = Vue2Leaflet;
new Vue({
el: '#app',
components: {
LMap,
LTileLayer,
LMarker
},
data() {
return {
zoom: 14,
center: L.latLng(47.413220, -1.219482),
url: 'http://{s}.tile.osm.org/{z}/{x}/{y}.png',
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors',
markers: [
L.latLng(47.412, -1.218),
L.latLng(47.413220, -1.219482),
L.latLng(47.414, -1.22),
]
}
},
methods: {
removeMarker(index) {
this.markers.splice(index, 1);
},
addMarker(event) {
this.markers.push(event.latlng);
}
}
});
html, body, #app {
height: 100%;
margin: 0;
}
<script src="https://unpkg.com/vue@latest/dist/vue.js"></script>
<link href="https://unpkg.com/[email protected]/dist/leaflet.css" rel="stylesheet" />
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
<script src="https://unpkg.com/[email protected]/dist/vue2-leaflet.js"></script>
<div id="app">
<l-map :zoom="zoom" :center="center" @click="addMarker">
<l-tile-layer :url="url" :attribution="attribution"></l-tile-layer>
<l-marker v-for="marker, index in markers" :lat-lng="marker" @click="removeMarker(index)"></l-marker>
</l-map>
</div>
<
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With