Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Leaflet and Vuejs. How to add a new Marker onclick in the map?

Tags:

vue.js

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:'&copy; <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

like image 611
yassine j Avatar asked Feb 03 '19 01:02

yassine j


1 Answers

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: '&copy; <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>
<
like image 132
Roy J Avatar answered Sep 24 '22 07:09

Roy J