I am using Map
from react-map-gl
to display several markers in a map. I also use Layers and Source to have my markers in clusters. But I have a problem because I can have multiple points with the exact same coordinate and those points end up overlaying each other when zooming in (it seems that there is only one marker in the position when there are multiple).
I have installed mapboxgl-spiderifier to overcome this problem but I can't seem to get it working.
Here's some of my code:
const [spiderifier, setSpiderifier] = useState(null);
const ref = useRef();
...
const onMapLoad = React.useCallback(() => {
setSpiderifier(
new MapboxglSpiderifier(ref.current.getMap(), {
onClick: function (e, spiderLeg) {
e.stopPropagation();
console.log("Clicked on ", spiderLeg);
},
markerWidth: 100,
markerHeight: 100,
})
);
}, []);
const onClick = (event) => {
const feature = event.features[0];
if (feature.layer.id === "clusters") {
const clusterId = feature.properties.cluster_id;
const mapboxSource = ref.current.getSource("classesandtrainers");
if (location.zoom >= 12) {
mapboxSource.getClusterLeaves(
clusterId,
100,
0,
function (err, leafFeatures) {
if (err) {
return console.error("error while getting leaves of a cluster", err);
}
let markers = leafFeatures.map((leafFeature) => {
return leafFeature.properties;
});
spiderifier.spiderfy(event.lngLat, { ...geoJson, features: markers });
}
);
return;
}
mapboxSource.getClusterExpansionZoom(clusterId, (err, zoom) => {
if (err) {
return;
}
ref.current.easeTo({
center: feature.geometry.coordinates,
zoom,
duration: 500,
});
});
}
};
...
return (
<Map
ref={ref}
{...location}
onLoad={onMapLoad}
onMove={(evt) => setLocation(evt.viewState)}
onClick={onClick}
mapStyle="mapbox://styles/flxbl/cl92sjxf4001g15la7upwjij2"
mapboxAccessToken={process.env.mapbox_key}
style={{ width: "100%", height: "100%", margin: 0, padding: 0 }}
interactiveLayerIds={[clusterLayer.id, unclusteredPointLayer.id]}
>
<Source
id="classesandtrainers"
type="geojson"
data={sourceData()}
cluster={true}
clusterMaxZoom={14}
clusterRadius={50}
>
<Layer {...clusterLayer} />
<Layer {...clusterCountLayer} />
<Layer {...unclusteredPointLayer} />
</Source>
<ScaleControl position="bottom-right" />
{renderPopup()}
</Map>
Can someone please help me?