Error: Unable to iterate through events using forEach method in Leaflet and VueJS due to TypeError

I am currently working on a Vue project and I want to incorporate Leaflet maps within my components. The map is displaying correctly, but I encounter an error when attempting to add a marker to the map. The specific error message that I receive is:

Uncaught TypeError: events.forEach is not a function at VueComponent.addEvents (VM2537 Map.vue:35) at e.boundFn (VM2533 vue.esm.js:191) at HTMLAnchorElement. (leaflet.contextmenu.js:328) at 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>

Answer №1

Greetings New2Dis,

I have provided an example of your code 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("hello")
      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 made some adjustments to ensure it functions correctly, such as replacing $store since I do not have access to it, and fixing the issue with removeEvent method.

In addition, I have developed a plugin to simplify using Leaflet with Vue. You can access it here There is also a plugin available for Cluster group here

Feel free to test it out and share your feedback with me.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The module you are trying to access at './server/controller/controller.js' does not contain an export with the name 'default'

I'm fairly new to backend development and I've recently started using ES6 modules in my project. However, when I try to import the controller file into index.js and run the project, I encounter the following error: Syntax Error: The requested mo ...

Are you ready to create a Modal Factory?

For a while now, I have been utilizing modals in various front-end frameworks to communicate with users in my applications. Typically, the process involves defining the modal's html and then rendering it through a click event. As my apps continue to ...

Distributing v-model to a descendant component

I am facing an issue with my component structure: Form.vue -> FormTextInput.vue -> TextInput.vue. In Form.vue, I am using v-model to handle reactive data with FormTextInput.vue. How can I effectively pass this property down to TextInput.vue and ensur ...

Learn how to retrieve JSON data from the Yahoo Finance REST API using Angular 2

Currently, I am in the process of developing an application that needs to fetch data from the Yahoo Finance REST API. To retrieve a table for the symbol "GOOG," I have implemented the following code: export class ActService{ act = []; url = 'http ...

How can I customize button colors in react-bootstrap components?

Changing colors in react-bootstrap may be a challenge, but I'm looking to customize the color of my button beyond the primary options. Any suggestions on how I can achieve this using JS and SCSS? ...

How to visually represent options without labels using icons in Material UI Autocomplete

My options are structured as follows: const options = ['option1', 'option2']; I am looking to display the options with icons like this: https://i.stack.imgur.com/aubHS.png The current code for rendering options looks like this: ...

Error: The term "Worker" is undefined in a new Nextjs project

I'm currently looking into an issue where I am attempting to import a webpacked javascript file into a NextJS project that utilizes Worker, but I keep encountering the error message ReferenceError: Worker is not defined. I've simplified it down t ...

Error: Unable to update Ember Array - Property 'destroy' cannot be read because it is undefined

Is there a way to efficiently update an Ember Array so that changes in the array reflect in the view? Take a look at this simplified code snippet - cacheArr: Em.A([]), count: 1, updateFxn: function() { this.incrementProperty(count); devObj = Embe ...

Working with Angular to add various items to an array based on multiple conditions

Currently, I am a beginner in TypeScript and currently involved in an Angular project. As part of my work, I need to make an API call and perform various operations on the received data: public data_Config: IConfig[] = []; this.getService.Data(input).sub ...

Is it possible to upload files without using AJAX and instead through synchronous drag-and-drop functionality in the foreground?

Currently, my website has a standard <input type="file"> file upload feature that sends data to the backend upon form submission. I am looking to enhance the functionality of the form by allowing users to drag and drop files from anywhere within the ...

Updating the geometry of vertices after rotating or moving an object

I've been experimenting with using position and rotation values to transform a mesh, but now I'd like to modify the geometry vertices directly in x, y, and z coordinates while freeing or resetting the rotation and position values. I'm not qu ...

Implementing real-time time updates using php ajax technology

It's fascinating how websites can update the time dynamically without using ajax requests. I currently have a comment system in place. $('#comment').click(function(){ $.post(url,{ comment : $(this).siblings('textarea.#commen ...

Sending a POST requestIs there an issue with performing

Below is my JavaScript code snippet: $('document').ready(function () { $('#filterSub').click(function (evt) { var data = $('form').serialize(); var gender = $('#gender').html(); $.post(& ...

The concept of reducing functions in JavaScript and the significance of extra brackets

My function looks like this: function ross(array) { return array.map(function(data) { return data.reduce(function(obj, item) { obj[item[0]] = item[1]; return obj; }, {}); }); } ross(array); This code is responsible for converting a ...

Controlling the v-model value of a v-select within a v-for loop

I have set up a table of members using a v-for loop, and certain users have the ability to manage other members based on their role. I have implemented some checks to prevent unauthorized roles from intervening, but the full list of checks is carried out o ...

What is the best way to create a clickable entity that is being dynamically generated in a networked A-Frame environment?

I'm attempting to use a networked A-frame to create a new entity upon page load. I want to incorporate various functionalities, such as hover and click events, on these entities. However, my attempts to make them clickable have been unsuccessful. f ...

What is the best way to display a Bootstrap v4 modal box within a container div?

Exploring the capabilities of Bootstrap v4.0.0-alpha has been an exciting experience, but I have a specific requirement in mind: I want to place a modal box inside a container div instead of it covering the entire screen. https://i.sstatic.net/xyZ8X.jpg I ...

An Error with jQuery Autocomplete: "Callback is not Defined"

I am currently working on a jQuery script that involves autocomplete and selecting the correct value on the client side. Here is my functional code without the selected value (it displays all username available in my JSON): $(function() { $( "#us ...

Tips for making sure your published npm package respects the baseUrl specified in the tsconfig.json file

I am currently developing an npm library using TypeScript. Within our project configuration, we have specified a baseUrl in our tsconfig.json file. "baseUrl": "src", When referencing files within the src directory, we can simply use: src |-folderA ...

Enhance JQuery functionality using Typescript

Currently, I am in the process of developing a Typescript plugin that generates a DOM for Header and attaches it to the page. This particular project utilizes JQuery for handling DOM operations. To customize the plugin further, I aim to transmit config Opt ...