how can I calibrate this clusters? import { useRef, useState } from "react"; import {…
- User
how can I calibrate this clusters? import { useRef, useState } from "react"; import { Chip, Typography } from "@mui/material"; import { styled } from "@mui/material/styles"; import Map, { Layer, Popup, Source } from "react-map-gl"; import type { MapRef } from "react-map-gl";
import { MapMarker, MapProps } from "@/types/workspace-map-types";
import { countryCenters, MapboxMapController } from "../utils/map-utils";
const MAPBOX_TOKEN = import.meta.env.VITE_MAPBOX_TOKEN;
const StyledPopup = styled(Popup)(() => ({ "& .mapboxgl-popup-content": { borderRadius: 10, boxShadow: "0 4px 12px rgba(0, 0, 0, 0.2)", fontSize: 14, padding: 15, lineHeight: 2, }, "& .mapboxgl-popup-close-button": { fontSize: 20, }, }));
export function MapMapboxCluster({ selectedCountryId, markerLimit, markers }: MapProps) { const center = countryCenters[selectedCountryId ?? "PL"]; const [selectedMarker, setSelectedMarker] = useState<MapMarker | null>(null); const mapRef = useRef<MapRef | null>(null);
function convertToGeoJSON(markers: MapMarker[]) { return { type: "FeatureCollection", features: markers.slice(0, markerLimit).map((marker) => ({ type: "Feature", properties: { name: marker.name, available: marker.available, }, geometry: { type: "Point", coordinates: [marker.lng, marker.lat], }, })), }; } function handleMapClick(e: mapboxgl.MapMouseEvent) { const map = e.target; const clusterFeatures = map.queryRenderedFeatures(e.point, { layers: ["clusters"], }); if (clusterFeatures.length > 0) { const cluster = clusterFeatures[0]; const clusterId = cluster.properties?.cluster_id; const mapboxSource = map.getSource("markers") as mapboxgl.GeoJSONSource; mapboxSource.getClusterExpansionZoom(clusterId, (err, zoom) => { if (err) return; if (typeof zoom === "number") { map.easeTo({ center: (cluster.geometry as any).coordinates, zoom: zoom + 1.5, duration: 500, offset: [0, -100], }); } }); return; } const pointFeatures = map.queryRenderedFeatures(e.point, { layers: ["unclustered-point"], }); if (pointFeatures.length > 0) { const feature = pointFeatures[0]; const coords = feature.geometry?.type === "Point" ? feature.geometry.coordinates : null; if (coords) { const marker = { lat: coords[1], lng: coords[0], name: feature.properties?.name ?? "Unknown", available: feature.properties?.available === "true" || feature.properties?.available === true, countryCode: selectedCountryId ?? "PL", maxPower: feature.properties?.maxPower ?? "Unknown", }; setSelectedMarker(marker); } return; } setSelectedMarker(null); } if (!MAPBOX_TOKEN) { console.error("Missing Mapbox token."); return <div>Unable to load Mapbox map – missing token.</div>; } return ( <Map id="main-map" mapboxAccessToken={MAPBOX_TOKEN} initialViewState={{ latitude: center[0], longitude: center[1], zoom: 6, }} style={{ height: "100vh", width: "100%" }} mapStyle="mapbox://styles/mapbox/streets-v11" onClick={handleMapClick} ref={mapRef} onLoad={() => { const mapboxMap = mapRef.current?.getMap(); if (!mapboxMap) return; mapboxMap.on("mouseenter", "clusters", () => { mapboxMap.getCanvas().style.cursor = "pointer"; }); mapboxMap.on("mouseleave", "clusters", () => { mapboxMap.getCanvas().style.cursor = ""; }); mapboxMap.on("mouseenter", "unclustered-point", () => { mapboxMap.getCanvas().style.cursor = "pointer"; }); mapboxMap.on("mouseleave", "unclustered-point", () => { mapboxMap.getCanvas().style.cursor = ""; }); }} > <Source id="markers" type="geojson" data={convertToGeoJSON(markers)} cluster={true} clusterMaxZoom={10} clusterRadius={35} > <Layer id="clusters" type="circle" filter={["has", "point_count"]} paint={{ "circle-color": "#51bbd6", "circle-radius": 20, "circle-stroke-width": 1, "circle-stroke-color": "#fff", }} /> <Layer id="cluster-count" type="symbol" filter={["has", "point_count"]} layout={{ "text-field": "{point_count_abbreviated}", "text-size": 14, }} /> <Layer id="unclustered-point" type="circle" filter={["!", ["has", "point_count"]]} paint={{ "circle-color": "#007AFF", "circle-radius": 6, "circle-stroke-width": 1, "circle-stroke-color": "#fff", }} /> </Source> {selectedMarker && ( <StyledPopup latitude={selectedMarker.lat} longitude={selectedMarker.lng} closeOnClick={false} onClose={() => setSelectedMarker(null)} > <div style={{ minWidth: "140px" }}> <Typography variant="subtitle2" sx={{ mb: 0.5 }}> Point: <strong>{selectedMarker.name}</strong> </Typography> <Typography variant="body2" sx={{ mb: 0.5 }}> Max power: <strong>{selectedMarker.maxPower ?? "n/a"}</strong> </Typography> <Chip label={selectedMarker.available ? "Available" : "Unavailable"} color={selectedMarker.available ? "success" : "error"} size="small" variant="soft" /> </div> </StyledPopup> )} <MapboxMapController selectedCountryId={selectedCountryId ?? "PL"} /> </Map> );}
export default MapMapboxCluster;
- Assistant
Your Mapbox clustering setup looks mostly correct, but if you want to calibrate or fine-tune the clustering behavior, you can adjust a few key parameters and add some improvements for better control and user experience.
Key parameters to calibrate clusters:
-
clusterMaxZoom
Controls the maximum zoom level at which points will be clustered. Beyond this zoom, points will be shown individually.- Current:
clusterMaxZoom={10} - Adjust this to a higher zoom if you want clusters to persist longer (e.g., 12 or 14).
- Lower it if you want clusters to break apart earlier.
- Current:
-
clusterRadius
Controls the radius of each cluster when clustering points (in pixels).- Current:
clusterRadius={35} - Increase this to make clusters larger and group points that are farther apart.
- Decrease it to make clusters smaller and more granular.
- Current:
-
Cluster circle size and color
You can dynamically adjust the cluster circle radius and color based on the number of points in the cluster to give better visual feedback.
Example: Dynamic cluster circle radius and color
<Layer id="clusters" type="circle" filter={["has", "point_count"]} paint={{ // Color changes based on cluster size "circle-color": [ "step", ["get", "point_count"], "#51bbd6", // color for clusters with < 10 points 10, "#f1f075", // color for clusters with 10-30 points 30, "#f28cb1", // color for clusters with > 30 points ], // Radius changes based on cluster size "circle-radius": [ "step", ["get", "point_count"], 20, // radius for clusters with < 10 points 10, 30, // radius for clusters with 10-30 points 30, 40, // radius for clusters with > 30 points ], "circle-stroke-width": 1, "circle-stroke-color": "#fff", }} />
Additional tips for calibration:
- Adjust
clusterMaxZoomandclusterRadiusin the<Source>component:
<Source id="markers" type="geojson" data={convertToGeoJSON(markers)} cluster={true} clusterMaxZoom={14} // cluster until zoom level 14 clusterRadius={50} // cluster radius 50 pixels >-
Add a cluster expansion zoom offset
In yourhandleMapClick, you addzoom + 1.5when zooming into a cluster. You can tweak this offset to control how far the zoom goes when expanding a cluster. -
Consider adding cluster labels or tooltips
You can add more info in the cluster popup or on hover to help users understand cluster contents.
Summary of what to change for calibration:
<Source id="markers" type="geojson" data={convertToGeoJSON(markers)} cluster={true} clusterMaxZoom={14} // increase max zoom for clustering clusterRadius={50} // increase cluster radius for bigger clusters > <Layer id="clusters" type="circle" filter={["has", "point_count"]} paint={{ "circle-color": [ "step", ["get", "point_count"], "#51bbd6", 10, "#f1f075", 30, "#f28cb1", ], "circle-radius": [ "step", ["get", "point_count"], 20, 10, 30, 30, 40, ], "circle-stroke-width": 1, "circle-stroke-color": "#fff", }} /> {/* ... other layers */} </Source>
If you want me to help you with a specific behavior or problem related to clustering (e.g., clusters not expanding properly, performance issues, etc.), just let me know!
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.