MapConductor React SDK Samples

Capa GeoJSON | MapLibre | MapConductor React SDK

Ejemplo de Capa GeoJSON de MapConductor React SDK con MapLibre.

Este ejemplo interactivo muestra Capa GeoJSON mediante la abstracción de MapConductor sobre MapLibre.

Ejemplo de código

import { useMemo, useState } from 'react';
import { createGeoPoint, createMapCameraPosition, type GeoPoint } from '@mapconductor/js-sdk-core';
import { InfoBubble } from '@mapconductor/js-sdk-react';
import { MapLibreDesign, MapLibreMapView2D, useMapLibreViewState } from '@mapconductor/react-for-maplibre';
import {
  GeoJSONLayer,
  GeoJSONLayerState,
  GeoJSONParser,
  colorArgb,
} from '@mapconductor/react-geojson';
import '@mapconductor/react-for-maplibre/style.css';


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


  const initialCamera = createMapCameraPosition({
    position: createGeoPoint({ latitude: 35.6812, longitude: 139.7671 }),
    zoom: 12,
  });


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


  // (2) Preparar los datos y el estado de interacción
  const features = useMemo(() => GeoJSONParser.parseFeatures(JSON.stringify({
    type: 'FeatureCollection',
    features: [{ type: 'Feature', properties: { name: 'Sample railway' },
      geometry: { type: 'LineString', coordinates: [[139.75, 35.68], [139.77, 35.69], [139.79, 35.68]] },
    }],
  })), []);
  const [selected, setSelected] = useState<{
    position: GeoPoint; properties: Record<string, unknown>;
  } | null>(null);
  const layerState = useMemo(() => new GeoJSONLayerState({
    strokeColor: colorArgb(200, 250, 36, 29),
    strokeWidth: 6,
    onClick: (feature, position) => setSelected({ position: createGeoPoint(position), properties: feature.properties ?? {} }),
  }), []);
  const handleMapClick = (point: GeoPoint) => {
    if (!layerState.processClick(point, 10, mapViewState.cameraPosition.zoom)) setSelected(null);
  };


  // (3) Renderizar el mapa y sus capas


  return (
    <div style={{ height: 500, position: 'relative', display: 'flex', flexDirection: 'column' }}>
      <MapLibreMapView2D state={mapViewState} onMapClick={handleMapClick}>
        <GeoJSONLayer state={layerState} features={features} />
        {selected && (
          <InfoBubble position={selected.position}>
            <pre>{JSON.stringify(selected.properties, null, 2)}</pre>
          </InfoBubble>
        )}
      </MapLibreMapView2D>
    </div>
  );
}

Cómo funciona el código

El GeoJSON incluido contiene una línea de ferrocarril de ejemplo y no necesita servidor de datos.

handleMapClick llama a processClick con el zoom actual. onClick guarda las propiedades para el InfoBubble cuando hay un acierto; de lo contrario borra la selección.