The class name is not defined for a certain child element in the icon creation function

Currently, I am developing a Vue2 web application using Leaflet and marker-cluster. I am encountering an issue with the iconCreateFunction option in my template:

 <v-marker-cluster :options="{ iconCreateFunction: iconCreateClsPrg}">
          <l-marker ....> 
                <l-icon :class-name="programme.display ? 'custom-marker notDisplay' : 'custom-marker display'">

Here is a snippet of the iconCreateClsPrg method:

iconCreateClsPrg (marker_cluster) {
        const childs = marker_cluster.getAllChildMarkers();
         childs.forEach(child => {
            const cssCluster = child.options.icon.options.className;
            if (cssCluster && cssCluster.includes(this.css_marker_selected_simple)) {
                nbSelected++;
            }
          }
             ...
}

The issue arises when the cssCluster const sometimes becomes undefined without any clear reason. This unexpected behavior occurs sporadically at certain zoom levels that are inconsistent. Any suggestions or ideas would be greatly appreciated!

I have attempted to resolve this by refreshing the map, waiting for it to become defined (but faced issues with async methods), restarting the method from scratch, switching to a for loop instead of forEach, among other attempts. Unfortunately, none of these solutions have proven successful.

Answer №1

After much searching, I have finally discovered a technique to ensure that the icon is fully loaded by utilizing promises:

iconCreateClsPrg (marker_cluster) {
            let nbSelected = 0;
            try {
                const childs = marker_cluster.getAllChildMarkers();
                const promises = [];
                childs.forEach(child => {
                    // create promise to wait for all children
                    const promise = new Promise(resolve => {
                        // introduce a 0ms delay to allow the browser to render the page asynchronously
                        setTimeout(() => {
                            const cssCluster = child.options.icon.options.className;
                            if (cssCluster && cssCluster.includes(this.css_marker_selected_simple)) {
                                nbSelected++;
                            }
                            resolve();
                        }, 0);
                    });
                    promises.push(promise);
                });
                // wait for all children to be processed before proceeding
                Promise.all(promises).then(() => {
                    // complete the remaining tasks
                    const divIcon = new L.DivIcon({
                        html: htmlContent,
                        className: css_cluster,
                        iconSize: [30 + childCount, 30 + childCount],
                    });

                    // Ensure the cluster icon updates on the map after the promise has resolved
                    marker_cluster.setIcon(divIcon);
                });
            } catch (e) {
                // handle any errors encountered
            }
            // Start with a blank icon as a fallback
            return new L.DivIcon({
            });
        }

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

Utilizing AMAZON_COGNITO_USER_POOLS in conjunction with apollo-client: A comprehensive guide

Struggling to populate my jwtToken with the latest @aws-amplify packages, facing some challenges. Encountering an error when attempting to run a Query: Uncaught (in promise) No current user It seems that when using auth type AMAZON_COGNITO_USER_POOLS, I ...

unable to apply angular measurement inside quotation marks

What is the reason for this issue: <ul class="dropdown-menu"> <li ng-repeat="choice in dropDownItems"> <a class="btn" ng-click="mnuClick('{{choice}}')">{{choice}}</a> </li> </ul> However, this code wo ...

How to transfer data from an HTML form to PHP using AJAX

I've encountered an issue while working on a simple application that consists of one HTML file communicating with a PHP page using AJAX. Take a look at my index.html below: <!DOCTYPE html> <html><head> <meta charset="utf-8"> & ...

Using a JavaScript if statement to check the height of a specific HTML element

I have been struggling to figure out how to insert an if-else statement in JavaScript that references data about an HTML element. My objective is to create an "onclick" function that enlarges an image with a 200ms delay and another function that returns th ...

Modify the indentation format in CSS/JS

When the Tab key is pressed in an HTML page and the tabbed link gets highlighted, is it feasible to customize the style of that highlight? ...

Exploring the process of extracting a nested JSON value using Postman

I am currently facing an issue with parsing the json response from a post request, and then sending the parsed data to a put request. Here is the response body: { "createdBy": "student", "createdOn": "2019-06-18", "Id1": "0e8b9 ...

ESLint does not recognize the types from `@vuelidate/core` when importing them

When working with TypeScript, the following import statement is valid: import { Validation, ValidatorFn } from '@vuelidate/core' However, this code triggers an error in ESLint: The message "ValidatorFn not found in '@vuelidate/core' ...

React-highlightjs failing to highlight syntax code properly

I'm currently using the react-highlight library to highlight code snippets in my next.js application. However, I've encountered an issue with the code highlighting when using the a11y-dark theme. https://i.stack.imgur.com/ip6Ia.png Upon visitin ...

Error: Uncaught ReferenceError: d3 is undefined. The script is not properly referenced

Entering the world of web development, I usually find solutions on Stack Overflow. However, this time I'm facing a challenge. I am using Firefox 32 with Firebug as my debugger. The webpage I have locally runs with the following HTML Code <!DOCTYP ...

Animate an image to the right when clicked, then return it to the left with a second click

Seeking help with animating a set of images to move individually 300px right on first click, and then 300px left when clicked again. I'm currently facing an issue where my code is not working. It could be due to A) syntax errors or B) the images not ...

Can you elaborate on the users object found in the npm registry JSON response?

When looking at the json response of any npm package, such as jQuery for example, http://registry.npmjs.org/jquery, you may come across a dictionary called users. This dictionary contains usernames as keys and boolean values as the corresponding values. ...

Vue Pinia ensures that reactive state is only updated once, preventing unnecessary updates

In my Vue application, the structure is as follows: App.vue -GroupWrapper --GroupListing -PeopleWrapper --PeopleListing -ConversationWrapper Within my user store that utilizes Pinia, I primarily call user.findChats() in the App.vue component. Code snippe ...

Printing Apex Oracle reports using Internet Explorer

I am facing a challenge with printing my page that contains two interactive reports. To enable printing, I have utilized a JavaScript function that triggers window.print(). I have incorporated CSS to adjust the layout of my tables when printed. @media pr ...

Expanding a website banner slide to fill the entire width of the page

Is there a way to ensure that the banner images in the website below flow seamlessly? Currently, it seems like the current image is cut off on the left and part of the previous image shows up in its place. I'd like the current image to occupy the ent ...

React Material-UI Multiple Select with Checkboxes not displaying initial selections as checked

I am fairly new to working with React and MUI, so please bear with me. Currently, I am in the process of learning how to create Multiple Select Options with checkboxes by populating the Dropdown Options from an Array. Although I have set up the initial/de ...

Unexpected issue with sliding menu toggle implementation

I have been struggling to make a menu slide to the left when a button is clicked, and then slide back to its original position when the same button is clicked again. Although I have been using the toggle method, it doesn't seem to be working for me. I ...

Updating the data returned by the params function in Vue.js

Here is some code that I'm working with: <template> <div> <button @click="changeData(text)">Click Me!</button> <p>{{ text }}</p> </div> </template> <script> export de ...

Steps for accessing the controller scope from a directive nested within another directive:

I am in the process of developing code that is as generic as possible. Currently, I have 2 directives nested within each other, and I want the inner directive to call a method on the main controller's $scope. However, it seems to be requesting the m ...

Altering the hue of various stroke patterns

I've encountered an issue where I want to create skill bars that display my skills in percentages. Luckily, I found a great code that allows me to do this. Although I would prefer to do it myself, I haven't come across a good tutorial that teache ...

Adding a type declaration to the severity property in React Alert - A guide to Typescript

I've developed a type declaration object for the incoming data, but no matter what I try to define as the type for the property "severity", it's not happy. The options it wants (as displayed below) don't seem feasible. I'm curious if th ...