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

Guide to creating a rising or waving effect for text using CSS or JavaScript without the need for animation

Is there a way to style dynamic text like this using HTML? I'm open to using CSS or Javascript, as long as it does not involve animation. ...

Apply a Fade In transition to the ul li elements following a JavaScript toggle

I'm currently experimenting with implementing a Fade in from the right animation for the links displayed in the menu after toggling the menu body in the browser. Despite my efforts, I am unable to determine why the animation is not functioning as expe ...

Importing ReactDOM alone does not result in the rendering of anything

Having just started delving into the world of React, I've been grappling with getting a React app up and running. Despite my efforts, all I can manage to see is a blank page. Can anyone offer some assistance? HTML Markup (index.html) <html> & ...

Ways to sum up the values within a JSON object

Currently, I am using an AJAX call to fetch JSON data from an API. My goal now is to add up all the visits. This is what I have implemented so far. Any suggestions on how I can achieve that? $(document).ready(function() { var X = []; var Y = []; var d ...

Error message encountered when attempting to process json-encoded JavaScript using Ajax

I am struggling with an HTML document that includes: <li id="li_273" data-pricefield="special" data-pricevalue="0" > <label class="description" for="element_273">Helium Foil Balloon #1 </label> <div> ...

Is there a way to transpile a dependency within the node_modules directory when using Nuxt 2?

I have come across challenges when transpiling node_modules with Nuxt, but the latest version of Nuxt (2.0) seems to have addressed this issue by introducing a transpile option in the nuxt.config.js file. https://nuxtjs.org/api/configuration-build/#transp ...

Upcoming 13.4 Error: NEXT_REDIRECT detected in API routes

Here is the code snippet from my /app/api/auth/route.ts file: import { redirect } from 'next/navigation'; export async function GET(req: Request) { try { redirect('/dashboard'); } catch (error) { console.log(error); ...

What steps do I need to take in order to successfully implement the v-tabs component in Vuetify.js

I recently implemented the v-tabs component on a webpage. Currently, all three tabs in the example are displaying the same block of data (text): <template> <v-tabs fixed centered> <v-tabs-bar class="cyan" dark> <v-tabs-sl ...

Enhancing Efficiency with Laravel 5: Updating Multiple Data Entries

My Simple Todo App lacks the ability to persist multiple record updates simultaneously. The client-side version can be found here: http://codepen.io/anon/pen/bVVpyN Whenever I perform an action, I send an HTTP request to my Laravel API for data persistenc ...

creating an interactive table with the help of the useState hook

I'm new to JavaScipt and ReactJS, so I have a question that may seem obvious but I can't seem to figure it out. I am attempting to display my array in a table using useState, but currently I can only show the header. Additionally, if anyone know ...

Issues with data within a Vue.js pagination component for Bootstrap tables

Currently, my table is failing to display the data retrieved from a rest api (itunes), and it also lacks pagination support. When checking the console, I'm encountering the following error: <table result="[object Object],[object Object],[object Ob ...

Tips for eliminating the menu bar in the external window generated by an Electron application's URL

Looking for a solution to remove the menu bar from a window that opens with an external URL in an Electron application? Check out the code snippet below: windowObject.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrows ...

Enlarging the modal overlay

My Angular/Bootstrap app features a small text area within a modal window that often contains lengthy content exceeding the size of the textarea and modal itself. I am looking to incorporate a button within the modal window that, when clicked, opens a lar ...

Is there a way to adjust the width of a table cell in Material UI using React?

I encountered a problem where I am attempting to adjust the width of a table cell, specifically in Typescript. However, I am only able to choose between medium and small sizes for TableCellProps. Is there a workaround for this issue? I am looking to expand ...

Incorporate a course within the conditional statement

Currently, I'm working on the development of an input site and one of my goals is to highlight empty fields. My plan is to check if a field is empty using an if statement and then apply a specific class that will serve this purpose. This is the JavaS ...

Implementing automatic activation of a tab upon page load using Angular

I am currently working with a set of Bootstrap nav pills in my navigation bar. The 'ng-init' code in my Angular script sets the 'dateState' to 'past' on page load. However, I have noticed that the 'Past Events' nav p ...

Integrating a Vue application with an OpenId provider using the OpenId Connect library

Currently, I am in the process of developing a Single Page Application with Vue on the client-side and Java Spring REST APIs on the backend. My goal is to add security measures using OpenId Connect, specifically with RapidIdentity as the provider. Unlike ...

Sending a Thunk to the store using Typescript

Within my primary store.ts file, the following code is present: const store = createStore( rootReducer, composeWithDevTools(applyMiddleware(thunk)) ); store.dispatch(fetchUser()); Upon initial rendering, an action is dispatched to fetchUser in ord ...

Converting Typescript objects containing arrays into a single array

Looking for some assistance with this problem :) I am trying to convert the object into an array with the following expected result: result = [ { id: 'test-1', message: 'test#1.1' }, { id: 'test-1', mess ...

dividing values for future angular use

Within my code, I have the following snippet: color: {{item.color}} This setup functions well when dealing with single items. However, there are instances where I encounter a value such as: white|black Is there a way to separate these values into indiv ...