Customizing Marker Clusters with ui-leaflet: A guide on changing marker cluster colors

I'm trying to customize the markerCluster color in a non-default way. I've been exploring the API and it looks like the recommendation is to modify a divIcon after creation, possibly like this:

var markers = L.markerClusterGroup({
iconCreateFunction: function(cluster) {
    return L.divIcon({ html: '<b>' + cluster.getChildCount() + '</b>' });
}
});

https://github.com/Leaflet/Leaflet.markercluster

Previously, I was populating data upon creation, somewhat similar to this:

layers: {
                baselayers: {
                    osm: {
                        name: 'OpenStreetMap',
                        type: 'xyz',
                        url: 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
                        layerOptions: {
                            subdomains: ['a', 'b', 'c'],
                            attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
                            continuousWorld: true
                        }
                    },
                    cycle: {
                        name: 'OpenCycleMap',
                        type: 'xyz',
                        url: 'http://{s}.tile.opencyclemap.org/cycle/{z}/{x}/{y}.png',
                        layerOptions: {
                            subdomains: ['a', 'b', 'c'],
                            attribution: '&copy; <a href="http://www.opencyclemap.org/copyright">OpenCycleMap</a> contributors - &copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
                            continuousWorld: true
                        }
                    }
                },
                overlays: {
                    hillshade: {
                        name: 'Hillshade Europa',
                        type: 'wms',
                        url: 'http://129.206.228.72/cached/hillshade',
                        visible: true,
                        layerOptions: {
                            layers: 'europe_wms:hs_srtm_europa',
                            format: 'image/png',
                            opacity: 0.25,
                            attribution: 'Hillshade layer by GIScience http://www.osm-wms.de',
                            crs: L.CRS.EPSG900913
                        }
                    },
                    cars: {
                        name: 'Cars',
                        type: 'markercluster',
                        visible: true
                    }
                }
            },
            markers: {
                m1: {
                    lat: 42.20133,
                    lng: 2.19110,
                    layer: 'cars',
                    message: "I'm a moving car"
                },

I came across a similar site (and forked version) where I found some inspiration: https://github.com/tombatossals/angular-leaflet-directive/blob/master/examples/0216-layers-overlays-markercluster-example.html I tried adding an icon property with different colors but haven't had any success yet. My goal is to change the color when multiple types are clustered together. Any guidance would be greatly appreciated.

Thanks so much!

Answer №1

My misconception about using the divIcon led to a major issue. I wrongly believed that I had to change the color after creating it, but that was not the case. The solution turned out to be simple - just adding the code to my initial service:


cars: {
    name: 'Cars',
    type: 'markercluster',
    visible: true,
    layerOptions:{
        iconCreateFunction: function(cluster) {
            return L.divIcon({ html: '<b>' + cluster.getChildCount() + '</b>' });
        }
    }
}

I later discovered that the provided API functionality actually modifies the existing object rather than instantiating a new one. To instantiate it, you just need to add the variable names under the layerOptions key and refer to the variables on the API.

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

What is the best way to terminate a file upload initiated by ajaxSubmit() in jQuery?

A snippet of code I currently have is: UploadWidget.prototype.setup_form_handling = function() { var _upload_widget = this; $('form#uploader') .unbind('trigger-submit-form') // Possibly a custom method by our company . ...

How can I pass standard HTML as a component in React?

I need help creating a Higher Order Component (HOC) that accepts a wrapper component, but allows me to pass standard HTML elements as inner content. Here is an example of what I want to achieve: type TextLike = string | {type,content} const TextLikeRender ...

Updating Django database records with ajax

I'm currently working on a feature that involves filtering table data and updating the table using ajax. Here's what I have so far: Filter Form: <form id="search" method="POST" action="{% url 'article-filter' %}"> <input ...

Jquery ajax is failing to achieve success, but it is important not to trigger an error

My jQuery ajax request seems to be stuck in limbo - it's not throwing an error, but it also never reaches the success function. This is how my code looks: function delete() { $("input[name='delete[]']:checked").each(function() { ...

How can I implement the ternary operator in React Native and resolve my code issue?

Hello, I'm looking to implement the ternary operator in my code. Specifically, I want to render a FlatList if `cookup` has a value. However, if `cookup` is an empty array, I want to display some text instead. <FlatList data={cookUp} ...

Removing Multiple Object Properties in React: A Step-by-Step Guide

Is there a way in React to remove multiple object properties with just one line of code? I am familiar with the delete command: delete obj.property, but I have multiple object properties that need to be deleted and it would be more convenient to do this i ...

What methods can be used to defer the visibility of a block in HTML?

Is there a way to reveal a block of text (h4) after a delay once the page has finished loading? Would it be necessary to utilize setTimeout for this purpose? ...

Updating a section of a webpage using jQuery Mobile

I'm currently facing an issue with modifying a specific section of my webpage. Although this problem has been discussed before, I haven't found a satisfactory solution yet. The element in red on the page needs to change dynamically based on the ...

How can I dictate the placement of a nested Material UI select within a popper in the DOM?

Having trouble placing a select menu in a Popper. The issue is that the nested select menu wants to mount the popup as a sibling on the body rather than a child of the popper, causing the clickaway event to fire unexpectedly. Here's the code snippet f ...

Comparing the use of visibility: hidden with -webkit-transform: translate3d() within a PhoneGap application

Currently, I am creating a hybrid application using PhoneGap. As part of the design, I have several divs (each representing a page) that I toggle between by changing their visibility in CSS using "visibility: hidden" and "visible". However, I recently ca ...

After deploying to Heroku, the dynamic values in Angular are failing to appear

I recently encountered an issue with my Rails app that includes AngularJS components. While everything works perfectly on my local machine, I faced a problem after deploying it to Heroku. The dynamic Angular data values were not visible as expected; instea ...

What is the best way to implement jQuery after new elements have been added to the DOM?

I'm currently working on a Sentence Generator project. The program is designed to take a list of words and retrieve sentences from sentence.yourdictionary.com based on those words. The first sentence fetched from the website is displayed using the cod ...

Issues with plugins in Rails 4 are causing functionality to not be operating

I recently installed a template and encountered an issue with some of the JavaScript functionality. However, upon checking the compiled list of JavaScript files, I can see that all the files have loaded successfully and the CSS includes all the necessary f ...

What is the best way to retrieve information in Next.js when there are changes made to the data, whether it be new

Could you share a solution for fetching data in Next.js when data is added, deleted, or edited? I tried using useEffect with state to trigger the function but it only works when data is added. It doesn't work for edit or delete operations. I have mult ...

Attempting to implement a smooth fade effect on my image carousel using React-Native

Struggling to animate this image carousel in reactNative and feeling lost. Despite reading the documentation on animations, I can't figure out how to implement it properly. My attempts keep resulting in errors. Any assistance would be greatly apprecia ...

Troubleshooting React hooks: Child component dispatches not triggering updates in parent component

I've been trying to implement a method of passing down a reducer to child components using useContext. However, I encountered an issue where dispatching from a child component did not trigger a re-render in the parent component. Although the state ap ...

Identifying a specific item within an array

Can someone guide me on how to manipulate a specific object within an array of objects? For example: var myArray = [ {id: 1}, {id: 2}, {id: 3}, {id: 4} ] // Initial state with the 'number' set as an array state = { number: [] } // A functio ...

How to use Laravel to show a graph sourced from a separate database connection

Is it possible to create a pie or doughnut chart in Laravel using data from a separate database connection ('mysql2' in the .env file)? I have successfully generated charts from the main database, but this time I didn't migrate the second da ...

Upgrading from V4 to React-Select V5 causes form submission to return undefined value

Looking to upgrade from react-select v4 to v5. The form/field currently functions with v4 and Uniform, producing an output like this: { "skill": { "value": "skill1", "label": "Skill 1" } } After attempting the upgrade to V5, I'm getting a ...

Refreshing Three.js Scene to its Initial State

I am in the process of developing a Visual Editor where I can manipulate objects by adding, deleting, and transforming them. Currently, my scene only consists of a 5000x5000 plane as the floor. I am looking for a way to reset the scene back to its origin ...