未捕获的TypeError:events.forEach不是函数Leaflet和VueJS

时间:2018-02-22 03:22:14

标签: javascript vue.js leaflet

我正在制作一个vue项目,我想在我的组件中使用传单。我有地图显示但是当我尝试向地图添加标记时遇到错误。我得到了

  

未捕获的TypeError:events.forEach不是函数     在VueComponent.addEvents(VM2537 Map.vue:35)     在e.boundFn(VM2533 vue.esm.js:191)    在HTMLAnchorElement。 (leaflet.contextmenu.js:328)    在HTMLAnchorElement.r(leaflet.js:5)

<template>
  <div>
    <div id="map" class="map" style="height: 781px;"></div>
</div>
</template>

<script>
export default {
data() {
 return {
  map: [],
  markers: null
};
},
computed: {
 events() {
  return this.$store.state.events;
 }
},
watch: {
events(val) {
  this.removeEvents();
  this.addEvents(val);
}
},
methods: {
addEvents(events) {
  const map = this.map;
  const markers = L.markerClusterGroup();
  const store = this.$store;

  events.forEach(event => {
    let marker = L.marker(e.latlng, { draggable: true })
      .on("click", el => {
        store.commit("locationsMap_center", e.latlng);
      })
      //.bindPopup(`<b> ${event.id} </b> ${event.name}`)
      .addTo(this.map);
    markers.addLayer(marker);
  });

  map.addLayer(markers);
  this.markers = markers;
},
removeEvent() {
  this.map.removeLayer(this.markers);
  this.markers = null;
}
},
mounted() {
const map = L.map("map", {
  contextmenu: true,
  contextmenuWidth: 140,
  contextmenuItems: [
    {
      text: "Add Event Here",
      callback: this.addEvents
    }
  ]
}).setView([0, 0], 1);

L.tileLayer("/static/map/{z}/{x}/{y}.png", {
  maxZoom: 4,
  minZoom: 3,
  continuousWorld: false,
  noWrap: true,
  crs: L.CRS.Simple
}).addTo(map);
this.map = map;
}
};
</script>

1 个答案:

答案 0 :(得分:0)

New2Dis,

以下是您在jsfiddle中运行的示例。

  computed: {
    events: function () {
        return this.store.events;
    }
  },
  watch: {
    events: function (val) {
      this.removeEvents();    
      this.addEvents(val);
    }
    },
    methods: {
    addEvents(events) {
        console.log("hoi")
      const map = this.map;
      const markers = L.markerClusterGroup();
      const store = this.$store;

      events.forEach(event => {
        let marker = L.marker(event.latlng, { draggable: true })
          .on("click", el => {
            //store.commit("locationsMap_center", event.latlng);
          })
          .bindPopup(`<b> ${event.id} </b> ${event.name}`)
          .addTo(this.map);
        markers.addLayer(marker);
      });

      map.addLayer(markers);
      this.markers = markers;
    },
    removeEvents() {
        if (this.markers != null) {
        this.map.removeLayer(this.markers);
        this.markers = null;
      }
    }
  },

我确实更换了一些东西以使其正常工作,就像我没有的$ store一样,并且removeEvent没有正确编写,所以我不确定我实际修复了什么... < / p>

我还创建了一个插件,可以很容易地使用Leaflet和Vue。 你可以找到它here 您还可以找到群集组here

的插件

尝试一下,让我知道你的想法。