You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
and here map.getLayer(...).addMarker(Marker). or marker.addto(Layer/Source) or ...
As a result we should see a Cluster with custom markers.
Reacted by Christopher Bartling, Marc Köhlbrugge, Arden de Raaij, Liam McCabe, tinakc, Nico Prat, Oleg Romanovskyi, berpj, augerm, Cyprian Gepfert and 45 more
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.
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.
@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.
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?
// inspect a cluster on clickmap.on('click','clusters',function(e){varfeatures=map.queryRenderedFeatures(e.point,{layers: ['clusters']});varclusterId=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});});});
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.
@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 :)
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.
Reacted by berpj and Anand J.Kadhi
Reacted by Dhrumil Bhankhar, berpj, Anand J.Kadhi and demironmanx
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?
Reacted by clem, Rodion Mescheryakov, Marko Štimac, Jérôme Pott, Yohanes Keanoe, Duccio Armenise, Victor Locoman, Taufiq Muhammadi, Niyaz94, Karl Tarvas and 1 more
@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.
@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.
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;
}
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;
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 ?
@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)
@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 :)
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.
@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
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.
Activity
[-]Organize a custom Marker into the Cluster[/-][+]Support clustering for HTML "Marker"s[/+]lucaswoj commentedon Mar 24, 2017
Hi @D1M! We do not support clustering on
Markers, only onsymbollayers. This is a feature we may support in the future but have no immediate plans to add support.lucaswoj commentedon Mar 24, 2017
You can use custom icons with a
symbollayer via the newMap#addImagemethod (going out in the next release) or by adding the icons to your sprite in Studio.D1M commentedon Mar 24, 2017
@lucaswoj thanks, looking forward to see such feature in future releases of mapbox-gl!
lucaswoj commentedon Mar 24, 2017
Let's keep this issue open to track the feature 😄
1ec5 commentedon Mar 26, 2017
The Android and iOS analogue of this issue is being tracked in mapbox/mapbox-gl-native#5815.
realph commentedon Apr 5, 2017
+1 I too would like to have custom markers that work with clustering.
DarkKnight1992 commentedon May 18, 2017
+1 would really love to have this feature
peterqliu commentedon May 18, 2017
this is possible now, with https://github.com/mapbox/supercluster. Was originally built for leaflet maps, but can be adapted to GL marker.
DarkKnight1992 commentedon May 18, 2017
that's amazing, you guys are the best !!
DarkKnight1992 commentedon May 21, 2017
How to use this cluster plugin with custom html marker there is not much documentation about it ?? ;(
peterqliu commentedon May 21, 2017
@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.
65 remaining items
deathlock commentedon Apr 3, 2019
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?
andrewharvey commentedon Apr 4, 2019
@Smitraval The normal symbol clustering demo does this https://docs.mapbox.com/mapbox-gl-js/example/cluster/
deathlock commentedon Apr 4, 2019
@andrewharvey Thank you very much for your quick reply. I will try the same and update the final result here for future reference.
deathlock commentedon Apr 7, 2019
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 () {
See those red points in map? I need to change them with HTML div. Any help would be appreciated.
NeonCreativeStudios commentedon Jun 12, 2019
@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 :)
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.

livthomas commentedon Jun 21, 2019
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?
mvtenney commentedon Jul 9, 2019
@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.
livthomas commentedon Jul 15, 2019
@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
onMoveEndcallback: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
animationendevent in Mapbox GL JS and so I find this to be the only reliable solution.Bjmn7 commentedon Feb 23, 2022
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.
thuanmb commentedon Feb 23, 2022
@Bjmn7 the issue should come from here:
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:
Bjmn7 commentedon Feb 23, 2022
@thuanmb Thank you very much, it works perfectly, great day to you.
Bjmn7 commentedon Feb 24, 2022
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 ?
thuanmb commentedon Feb 25, 2022
@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.Markerinstance) or remove it from the map (usingmap.removeLayerfunction)OlejarzRafal commentedon Feb 23, 2023
@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
arenarium-dev commentedon Feb 19, 2026
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.
If you want check it out: https://arenarium.dev/?demo=bookings