[Vuejs]-Uncaught TypeError: events.forEach is not a function Leaflet and VueJS

0👍

New2Dis,

Here is your example running in a 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;
      }
    }
  },

I did replace some things to make it works, like the $store as I don’t have it, and removeEvent was not written correctly, so I’m not sure what I actually fixed…

I have also created a plugin to make it easy to use Leaflet with Vue.
You can find it here
You will also find a plugin for Cluster group here

Give it a try and let me know what you think.

Leave a comment