传单和Vuejs。如何在地图中添加新的标记onclick?

yas*_*e j 2 vue.js

我想在我的传单地图中添加和删除标记。我发现这个好话题,但是代码在JS中。

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

我的代码是这样的:

<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>
Run Code Online (Sandbox Code Playgroud)

也许我应该首先在点击时创建一个函数,像这样:

<l-map :zoom="zoom" :center="center" v-on:click="addMarker"></l-map>
Run Code Online (Sandbox Code Playgroud)

然后我在方法中写了正确的addMarker函数。但是我找不到适合的文档。

我也想获得新标记在数据中的位置。

谢谢

Roy*_*y J 5

事实证明,这确实非常容易。使用带有v-for而不是单个标记的数组。单击标记可在该索引处剪接标记。单击地图会使用latlng创建一个新标记。下面的代码段基于此小提琴

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);
    }
  }
});
Run Code Online (Sandbox Code Playgroud)
html, body, #app {
  height: 100%;
  margin: 0;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/vue@latest/dist/vue.js"></script>
<link href="https://unpkg.com/leaflet@1.0.3/dist/leaflet.css" rel="stylesheet" />
<script src="https://unpkg.com/leaflet@1.0.3/dist/leaflet.js"></script>
<script src="https://unpkg.com/vue2-leaflet@1.0.1/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>
<
Run Code Online (Sandbox Code Playgroud)