Skip to content

Support clustering for HTML "Marker"s #4491

Closed

Description

@D1M

Hello!
As we can see here https://www.mapbox.com/mapbox-gl-js/example/custom-marker-icons/
we could create a custom Marker and add it to map.
e.g. new mapboxgl.Marker(...).setLngLat(...).addTo(map);

I'm trying to find the way how to add marker to the layer and organize into the Cluster.
Smth like https://www.mapbox.com/mapbox-gl-js/example/cluster/ but with custom Markers:

  1. var map = new mapboxgl.Map...
  2. map.addSource(...);
  3. map.addLayer(...);
  4. and here map.getLayer(...).addMarker(Marker). or marker.addto(Layer/Source) or ...
    As a result we should see a Cluster with custom markers.

Activity

  1. changed the title [-]Organize a custom Marker into the Cluster[/-] [+]Support clustering for HTML "Marker"s[/+] on Mar 24, 2017
  2. lucaswoj commented on Mar 24, 2017

    @lucaswoj
    Contributor

    Hi @D1M! We do not support clustering on Markers, only on symbol layers. This is a feature we may support in the future but have no immediate plans to add support.

  3. lucaswoj commented on Mar 24, 2017

    @lucaswoj
    Contributor

    You can use custom icons with a symbol layer via the new Map#addImage method (going out in the next release) or by adding the icons to your sprite in Studio.

  4. D1M commented on Mar 24, 2017

    @D1M
    Author

    @lucaswoj thanks, looking forward to see such feature in future releases of mapbox-gl!

  5. lucaswoj commented on Mar 24, 2017

    @lucaswoj
    Contributor

    Let's keep this issue open to track the feature 😄

  6. 1ec5 commented on Mar 26, 2017

    @1ec5
    Contributor

    The Android and iOS analogue of this issue is being tracked in mapbox/mapbox-gl-native#5815.

  7. realph commented on Apr 5, 2017

    @realph

    +1 I too would like to have custom markers that work with clustering.

  8. DarkKnight1992 commented on May 18, 2017

    @DarkKnight1992

    +1 would really love to have this feature

  9. peterqliu commented on May 18, 2017

    @peterqliu
    Contributor

    this is possible now, with https://github.com/mapbox/supercluster. Was originally built for leaflet maps, but can be adapted to GL marker.

  10. DarkKnight1992 commented on May 18, 2017

    @DarkKnight1992

    that's amazing, you guys are the best !!

  11. DarkKnight1992 commented on May 21, 2017

    @DarkKnight1992

    How to use this cluster plugin with custom html marker there is not much documentation about it ?? ;(

  12. peterqliu commented on May 21, 2017

    @peterqliu
    Contributor

    @DarkKnight1992 you are correct that there is no documentation specifically combining supercluster with GL custom markers. The former does provide GeoJSON as output, though, which you can figure out how to adapt as an input for the latter.

  13. 65 remaining items

  14. deathlock commented on Apr 3, 2019

    @deathlock

    Excellent work!! Although, I think the only thing missing is when we click on the marker it should zoom in the map. Is there any way I can achieve this functionality?

  15. andrewharvey commented on Apr 4, 2019

    @andrewharvey
    Collaborator

    @Smitraval The normal symbol clustering demo does this https://docs.mapbox.com/mapbox-gl-js/example/cluster/

    // inspect a cluster on click
    map.on('click', 'clusters', function (e) {
      var features = map.queryRenderedFeatures(e.point, { layers: ['clusters'] });
      var clusterId = features[0].properties.cluster_id;
      map.getSource('earthquakes').getClusterExpansionZoom(clusterId, function (err, zoom) {
        if (err)
          return;
     
        map.easeTo({
          center: features[0].geometry.coordinates,
          zoom: zoom
        });
      });
    });
  16. deathlock commented on Apr 4, 2019

    @deathlock

    @andrewharvey Thank you very much for your quick reply. I will try the same and update the final result here for future reference.

  17. deathlock commented on Apr 7, 2019

    @deathlock

    Hi @andrewharvey , Using your example I have successfully created marker clusters with images, However I am still stuck at a point where I need to replace un-clustered points with custom html div. Here is my code

    `map.on('load', function () {

            // Add a new source from our GeoJSON data and set the
            // 'cluster' option to true. GL-JS will add the point_count property to your source data.
            map.addSource("hotels", {
                type: "geojson",
                // Point to GeoJSON data. This example visualizes all M1.0+ earthquakes
                // from 12/22/15 to 1/21/16 as logged by USGS' Earthquake hazards program.
                data: hotelGeo,//"https://docs.mapbox.com/mapbox-gl-js/assets/earthquakes.geojson",
                cluster: true,
                //clusterMaxZoom: 14, // Max zoom to cluster points on
                //clusterRadius: 40 // Radius of each cluster when clustering points (defaults to 50)
            });
    
            map.addLayer({
                id: "clusters",
                type: "circle",
                source: "hotels",
                filter: ["has", "point_count"],
                paint: {
                    // Use step expressions (https://docs.mapbox.com/mapbox-gl-js/style-spec/#expressions-step)
                    // with three steps to implement three types of circles:
                    //   * Blue, 20px circles when point count is less than 100
                    //   * Yellow, 30px circles when point count is between 100 and 750
                    //   * Pink, 40px circles when point count is greater than or equal to 750
                    //"circle-color": "blue",
                    "circle-radius": 0
                }
            });
    
            // map.addLayer({
            //     id: "cluster-count",
            //     type: "symbol",
            //     source: "hotels",
            //     filter: ["has", "point_count"],
            //     layout: {
            //         "text-field": "{point_count_abbreviated}",
            //         "text-font": ["DIN Offc Pro Medium", "Arial Unicode MS Bold"],
            //         "text-size": 0
            //     }
            // });
    
            map.addLayer({
                id: "unclustered-point",
                type: "circle",
                source: "hotels",
                filter: ["!=", "cluster", true],
                paint: {
                    "circle-color": "red",
                    "circle-radius": 4,
                    "circle-stroke-width": 1,
                    "circle-stroke-color": "#fff"
                }
            });
    
            // objects for caching and keeping track of HTML marker objects (for performance)
            var markers = {};
            var markersOnScreen = {};
            var coordinates = {};
    
            function updateMarkers() {
                var newMarkers = {};
                var features = map.querySourceFeatures('hotels');
                // for every cluster on the screen, create an HTML marker for it (if we didn't yet),
                // and add it to the map if it's not there already
                for (var i = 0; i < features.length; i++) {
                    if (!features[i]) continue;
    
                    var coords = features[i].geometry.coordinates;
                    var props = features[i].properties;
                    if (!props.cluster) continue;
                    var id = props.cluster_id;
                    coordinates[id] = coords;
    
                    // console.log("check id", id)
    
                    var marker = markers[id];
                    if (!marker) {
    
                        /*** For cluster */
                        var el = document.createElement('div');
                        var features = map.queryRenderedFeatures({ layers: ['clusters'] });
    
                        if (!features[i]) continue;
    
                        var point_count = features[i].properties.point_count_abbreviated;
                        el.className = 'marker';
                        el.id = id;
                        el.style.backgroundImage = 'url("' + Marker + '")';
                        el.style.width = '41px';
                        el.style.height = '48px';
                        el.innerHTML = "<span style='width: 41px;line-height: 42px;text-align:center;display:block'>" + point_count + "</span>"
    
                        // console.log("check counts", point_count);
                        marker = markers[id] = new mapboxgl.Marker({ element: el }).setLngLat(coords);
    
                        el.addEventListener('click', () => {
                            var features = map.queryRenderedFeatures({ layers: ['clusters'] });
                            if (!features[0]) return;
                            var clusterId = features[0].properties.cluster_id;
                            map.getSource('hotels').getClusterExpansionZoom(clusterId, function (err, zoom) {
                                if (err)
                                    return;
    
                                // map.easeTo({
                                //     center: coordinates[el.id],
                                //     zoom: zoom
                                // });
    
                                map.flyTo({
                                    center: coordinates[el.id],
                                    zoom: zoom,
                                    speed: .75
                                });
    
                                //console.log("check coords", coordinates)
                                // for every marker we've added previously, remove those that are no longer visible
                                //map.off("zoom");
    
                            });
    
                        }
    
                        );
    
                    }
                    newMarkers[id] = marker;
    
                    if (!markersOnScreen[id])
                        marker.addTo(map);
                }
                //console.log("check coords", coordinates)
                // for every marker we've added previously, remove those that are no longer visible
                for (id in markersOnScreen) {
                    //console.log("in for loop", newMarkers[id])
                    if (!newMarkers[id])
                        markersOnScreen[id].remove();
                }
                markersOnScreen = newMarkers;
            }
    
            // after the GeoJSON data is loaded, update markers on the screen and do so on every map move/moveend
            map.on('data', function (e) {
                if (e.sourceId !== 'hotels' || !e.isSourceLoaded) return;
                map.on('zoom', updateMarkers);
                map.on('moveend', updateMarkers);
                updateMarkers();
            });
    
            map.on('mouseenter', 'clusters', function () {
                map.getCanvas().style.cursor = 'pointer';
            });
            map.on('mouseleave', 'clusters', function () {
                map.getCanvas().style.cursor = '';
            });
        });`
    

    See those red points in map? I need to change them with HTML div. Any help would be appreciated.

    hotels-map

  18. NeonCreativeStudios commented on Jun 12, 2019

    @NeonCreativeStudios

    @Smitraval I've simplified your code and it now works for custom markers and clusters. And at the end of the updateMarkers function, there's a simple loop that removes unused markers and clusters :)

    image

        map.addSource("addresses", {
            type: "geojson",
            data: geojson,  //"https://docs.mapbox.com/mapbox-gl-js/assets/earthquakes.geojson",
            cluster: true,
            clusterMaxZoom: 13, // Max zoom to cluster points on
            clusterRadius: 50 // Radius of each cluster when clustering points (defaults to 50)
        });
        
        map.addLayer({
            id: "clusters",
            type: "circle",
            source: "addresses",
            filter: ["has", "point_count"],
            paint: {
                "circle-radius": 0
            }
        });
    
    
        // Store IDs and cluster/marker HTMLElements
        const markers = new Map();
    
        function updateMarkers(){
            const features = map.querySourceFeatures('addresses');
            const keepMarkers = [];
    
            for (let i = 0; i < features.length; i++) {
                const coords = features[ i ].geometry.coordinates;
                const props = features[ i ].properties;
                const featureID = features[ i ].id;
                
                const clusterID = props.cluster_id || null;
    
                if (props.cluster && markers.has('cluster_'+clusterID)) {
    
                    //Cluster marker is already on screen
                    keepMarkers.push('cluster_'+clusterID);
    
                } else if (props.cluster) {
    
                    //This feature is clustered, create an icon for it and use props.point_count for its count
    
                    var el = document.createElement('div');
                    el.className = 'mapCluster';
                    el.style.width = '60px';
                    el.style.height = '60px';
                    el.style.textAlign = 'center';
                    el.style.color = 'white';
                    el.style.background = '#16d3f9';
                    el.style.borderRadius = '50%';
                    el.innerText = props.point_count;
                    const marker = new mapboxgl.Marker(el).setLngLat(coords);
                    marker.addTo(map);
                    keepMarkers.push('cluster_'+featureID);
                    markers.set('cluster_'+clusterID,el);
                    
                } else if (markers.has(featureID)) {
    
                    //Feature marker is already on screen
                    keepMarkers.push(featureID);
    
                } else {
                    
                    //Feature is not clustered and has not been created, create an icon for it
                    const el = new Image();
                    el.style.backgroundImage = 'url(https://placekitten.com/g/50/50)';
                    el.className = 'mapMarker';
                    el.style.width = '50px';
                    el.style.height = '50px';
                    el.style.borderRadius = '50%';
                    el.dataset.type = props.type;
                    const marker = new mapboxgl.Marker(el).setLngLat(coords);
                    marker.addTo(map);
                    keepMarkers.push(featureID);
                    markers.set(featureID,el);
                    
                }
                
            }
    
            //Let's clean-up any old markers. Loop through all markers
            markers.forEach((value,key,map) => {
                //If marker exists but is not in the keep array
                if (keepMarkers.indexOf(key) === -1) {
                    console.log('deleting key: '+key);
                    //Remove it from the page
                    value.remove();
                    //Remove it from markers map
                    map.delete(key);
                }
            });
    
        };`
    
        map.on('data', function (e) {
            if (e.sourceId !== 'addresses' || !e.isSourceLoaded) return;
            map.on('moveend', updateMarkers); // moveend also fires on zoomend
            updateMarkers();
        });
    

    Console output showing markers and clusters getting removed. They are removed when they go off screen, but also when they switch from a marker to a cluster and vice versa.
    image

  19. livthomas commented on Jun 21, 2019

    @livthomas

    I have just read this thread and if I understand it correctly it is simply not possible to easily create a cluster of HTML markers. You either need to add them as a GeoJSON layer and render them using images. Or you can add them to a map directly as markers but you need to manage the hiding logic manually. Am I right or am I missing something?

    I create my markers purely by using HTML and CSS. I want to add them to a cluster which would deal with the hiding logic and show the number of hidden markers (just like Leaflet plugins do it) without me having to implement anything. Is it possible or not?

  20. mvtenney commented on Jul 9, 2019

    @mvtenney

    @NeonCreativeStudios, thanks for your efforts! While running your example code, I am seeing the clustering work beautifully, but the max zoom seems to be ignored, and it is not unclustering into individual markers when zooming far enough.

  21. livthomas commented on Jul 15, 2019

    @livthomas

    @mvtenney I am not sure if you encountered the same problem as me but unclustering was very unreliable in my application so I had to add the following line to onMoveEnd callback:

    map.once('idle', () => updateMarkers());

    The only problem is that it waits not only for the zooming animation to end but also for map tiles loading so markers will appear after some time. However, AFAIK there is no animationend event in Mapbox GL JS and so I find this to be the only reliable solution.

  22. Bjmn7 commented on Feb 23, 2022

    @Bjmn7

    Hello,
    first of all, I thank you for your work to improve mapbox-gl-js.

    I have been using it for a few months now and I am very satisfied with it, both in terms of performance and ease of use. But for almost 2 weeks now, I’ve been dealing with a problem concerning the HTML clustering. I think I've identified where the problem comes from, from which function but I don't know how to solve it, so I'm calling you. Below, the result and the function that, for me, is responsible for this rendering.

    My data can change with different filters, the state of the data but also a date. When I change the date, some clusters present at the previous date remain on the map, they are not deleted as they should be in the function. And strangely, the ones that remain seem to prevent some new clusters from appearing.

    I thank you in advance for the time you will take to answer me.

    const markers: any = {};
    let markersOnScreen: any = {};
    
    function clusterConstructor(features: any, map: any) {
        const newMarkers: any = {};
    
        for (const feature of features) {
           const coords = feature.geometry.coordinates;
           const props = feature.properties;
    
           if (!props.cluster) continue;
           const id: number = props.cluster_id;
    
           let marker = markers[id];
           if (!marker) {
              const el = createDonutChart(props);
             marker = markers[id] = new mapboxgl.Marker({ element: el }).setLngLat(coords);
            }
          newMarkers[id] = marker;
          if (!markersOnScreen[id]) marker.addTo(map);
          }
        for (const id in markersOnScreen) {
           if (!newMarkers[id]) markersOnScreen[id].remove();
         }
        markersOnScreen = newMarkers;
       }
    

    Capture d’écran 2022-02-23 093724

  23. thuanmb commented on Feb 23, 2022

    @thuanmb

    @Bjmn7 the issue should come from here:

           let marker = markers[id];
    
           if (!marker) {
    
              const el = createDonutChart(props);
    
             marker = markers[id] = new mapboxgl.Marker({ element: el }).setLngLat(coords);
    
            }
    
           newMarkers[id] = marker;
           if (!markersOnScreen[id]) marker.addTo(map);
    

    in above code, if the marker already in here, you don't update with the new content (data for another day). that why it's not get update.
    you should always re-create/update the content of the marker (donut chart) when the date changed:

           let marker = markers[id];
           if (marker) {
              marker.remove()
            } 
            const el = createDonutChart(props);
            marker = markers[id] = new mapboxgl.Marker({ element: el }).setLngLat(coords);
            marker.addTo(map);
            newMarkers[id] = marker;
    
  24. Bjmn7 commented on Feb 23, 2022

    @Bjmn7

    @thuanmb Thank you very much, it works perfectly, great day to you.

  25. Bjmn7 commented on Feb 24, 2022

    @Bjmn7

    Hello, after multiple tests, it seems this solution slows down the map a lot when the function is fired by an idle event. If it is fired by a render event, it is even slower and the clusters move to the corner of the map at each render. Do you have any idea what could cause this @thuanmb ?

  26. thuanmb commented on Feb 25, 2022

    @thuanmb

    @Bjmn7 you can use some check to compare the props before re-rendering the clusters/markers. if the data (used to render the donut chart) has changed, we will re-render the chart. Otherwise keep the chart as is (by re-using previous mapboxgl.Marker instance) or remove it from the map (using map.removeLayer function)

  27. OlejarzRafal commented on Feb 23, 2023

    @OlejarzRafal

    @Smitraval Uprościłem twój kod i teraz działa on dla niestandardowych znaczników i klastrów. A na końcu funkcji updateMarkers znajduje się prosta pętla, która usuwa nieużywane znaczniki i klastry :)

    obraz

        map.addSource("addresses", {
            type: "geojson",
            data: geojson,  //"https://docs.mapbox.com/mapbox-gl-js/assets/earthquakes.geojson",
            cluster: true,
            clusterMaxZoom: 13, // Max zoom to cluster points on
            clusterRadius: 50 // Radius of each cluster when clustering points (defaults to 50)
        });
        
        map.addLayer({
            id: "clusters",
            type: "circle",
            source: "addresses",
            filter: ["has", "point_count"],
            paint: {
                "circle-radius": 0
            }
        });
    
    
        // Store IDs and cluster/marker HTMLElements
        const markers = new Map();
    
        function updateMarkers(){
            const features = map.querySourceFeatures('addresses');
            const keepMarkers = [];
    
            for (let i = 0; i < features.length; i++) {
                const coords = features[ i ].geometry.coordinates;
                const props = features[ i ].properties;
                const featureID = features[ i ].id;
                
                const clusterID = props.cluster_id || null;
    
                if (props.cluster && markers.has('cluster_'+clusterID)) {
    
                    //Cluster marker is already on screen
                    keepMarkers.push('cluster_'+clusterID);
    
                } else if (props.cluster) {
    
                    //This feature is clustered, create an icon for it and use props.point_count for its count
    
                    var el = document.createElement('div');
                    el.className = 'mapCluster';
                    el.style.width = '60px';
                    el.style.height = '60px';
                    el.style.textAlign = 'center';
                    el.style.color = 'white';
                    el.style.background = '#16d3f9';
                    el.style.borderRadius = '50%';
                    el.innerText = props.point_count;
                    const marker = new mapboxgl.Marker(el).setLngLat(coords);
                    marker.addTo(map);
                    keepMarkers.push('cluster_'+featureID);
                    markers.set('cluster_'+clusterID,el);
                    
                } else if (markers.has(featureID)) {
    
                    //Feature marker is already on screen
                    keepMarkers.push(featureID);
    
                } else {
                    
                    //Feature is not clustered and has not been created, create an icon for it
                    const el = new Image();
                    el.style.backgroundImage = 'url(https://placekitten.com/g/50/50)';
                    el.className = 'mapMarker';
                    el.style.width = '50px';
                    el.style.height = '50px';
                    el.style.borderRadius = '50%';
                    el.dataset.type = props.type;
                    const marker = new mapboxgl.Marker(el).setLngLat(coords);
                    marker.addTo(map);
                    keepMarkers.push(featureID);
                    markers.set(featureID,el);
                    
                }
                
            }
    
            //Let's clean-up any old markers. Loop through all markers
            markers.forEach((value,key,map) => {
                //If marker exists but is not in the keep array
                if (keepMarkers.indexOf(key) === -1) {
                    console.log('deleting key: '+key);
                    //Remove it from the page
                    value.remove();
                    //Remove it from markers map
                    map.delete(key);
                }
            });
    
        };`
    
        map.on('data', function (e) {
            if (e.sourceId !== 'addresses' || !e.isSourceLoaded) return;
            map.on('moveend', updateMarkers); // moveend also fires on zoomend
            updateMarkers();
        });
    

    Dane wyjściowe konsoli pokazujące usuwanie znaczników i klastrów. Są usuwane, gdy znikają z ekranu, ale także wtedy, gdy przechodzą ze znacznika do grupy i odwrotnie. obraz

    @NeonCreativeStudios @Bjmn7
    i have a similar problem, when zooming the cluster, the markers are not visible. I tried to solve this problem but I couldn't. Can anyone help

  28. arenarium-dev commented on Feb 19, 2026

    @arenarium-dev

    Hey I dont know if its still relevant but I've been building a plugin for mapbox and other map providers. It organizes your map markers and displays them in a way to maximize readability and clarity. It also improves the performance of displaying a large number of markers.

    Image

    If you want check it out: https://arenarium.dev/?demo=bookings

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions