MapConductor React SDK Samples

Agrupación de oficinas postales | MapLibre | MapConductor React SDK

Ejemplo de Agrupación de oficinas postales de MapConductor React SDK con MapLibre.

Este ejemplo interactivo muestra Agrupación de oficinas postales mediante la abstracción de MapConductor sobre MapLibre.

Ejemplo de código

import { useMemo, useState } from 'react';
import {
  ColorDefaultIcon,
  createGeoPoint,
  createGeoRectBounds,
  createMapCameraPosition,
  createMarkerState,
  type MarkerState,
} from '@mapconductor/js-sdk-core';
import { InfoBubble } from '@mapconductor/js-sdk-react';
import { MapLibreDesign, MapLibreMapView2D, useMapLibreViewState } from '@mapconductor/react-for-maplibre';
import { MarkerClusterGroup, type MarkerCluster } from '@mapconductor/react-marker-clustering';
import '@mapconductor/react-for-maplibre/style.css';


export default function App() {
  // (1) Crear el mapa


  const initialCamera = createMapCameraPosition({
    position: createGeoPoint({ latitude: 43.05, longitude: 141.31 }),
    zoom: 11,
  });


  const mapViewState = useMapLibreViewState({
    mapDesignType: MapLibreDesign.OsmBrightJa,
    cameraPosition: initialCamera,
  });


  // (2) Preparar los datos y el estado de interacción
  const postOffices = useMemo(() => [
    { id: 'maruyama', lat: 43.043751, lng: 141.305428, name: '円山西町簡易郵便局' },
    { id: 'jingu', lat: 43.057305, lng: 141.311483, name: '北海道神宮前郵便局' },
    { id: 'miyanomori', lat: 43.057305, lng: 141.303150, name: '札幌宮の森郵便局' },
    { id: 'araiyama', lat: 43.050833, lng: 141.298262, name: '札幌荒井山簡易郵便局' },
    { id: 'futagoyama', lat: 43.043085, lng: 141.318733, name: '札幌双子山郵便局' },
  ], []);
  const [selected, setSelected] = useState<MarkerState | null>(null);
  const postOfficeMarkers = useMemo(() => postOffices.map(office => createMarkerState({
    id: office.id,
    position: createGeoPoint({ latitude: office.lat, longitude: office.lng }),
    extra: office.name,
    onClick: markerState => setSelected(markerState),
  })), [postOffices]);
  const clusterIconProvider = (count: number) => new ColorDefaultIcon({
    fillColor: '#dc2626', label: String(count), labelTextColor: '#ffffff',
  });
  const zoomToCluster = (cluster: MarkerCluster) => {
    const bounds = createGeoRectBounds();
    postOfficeMarkers.filter(marker => cluster.markerIds.includes(marker.id))
      .forEach(marker => bounds.extend(marker.position));
    mapViewState.fitBounds(bounds, 60);
  };


  // (3) Renderizar el mapa y sus capas


  return (
    <div style={{ height: 500, position: 'relative', display: 'flex', flexDirection: 'column' }}>
      <MapLibreMapView2D state={mapViewState} onMapClick={() => setSelected(null)}>
        <MarkerClusterGroup
          markers={postOfficeMarkers}
          clusterIconProvider={clusterIconProvider}
          onClusterClick={zoomToCluster}
          minClusterSize={3}
          clusterRadiusPx={80}
        />
        {selected && <InfoBubble marker={selected}>{selected.extra as string}</InfoBubble>}
      </MapLibreMapView2D>
    </div>
  );
}

Cómo funciona el código

Agrupa una colección grande de marcadores y define un icono y una acción de clic personalizados mediante la API de extensiones.

El mismo arreglo postOfficeMarkers alimenta a MarkerClusterGroup en lugar de <Markers>, de modo que las oficinas cercanas se agrupan automáticamente al alejar el mapa.

clusterIconProvider dibuja la insignia del grupo, onClusterClick ejecuta zoomToCluster para expandirlo, y minClusterSize con clusterRadiusPx ajustan la intensidad con que se combinan los puntos.