MapConductor React SDK Samples

GeoJSON-Ebene | MapLibre | MapConductor React SDK

GeoJSON-Ebene-Beispiel des MapConductor React SDK mit MapLibre.

Dieses interaktive Beispiel zeigt GeoJSON-Ebene über die MapConductor-Abstraktion auf MapLibre.

Codebeispiel

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) Die Karte erzeugen


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


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


  // (2) Daten und Interaktionszustand vorbereiten
  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) Die Karte und ihre Overlays rendern


  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>
  );
}

Wie der Code funktioniert

Das eingebettete GeoJSON enthält eine Beispielbahnlinie und benötigt keinen Datenserver.

handleMapClick ruft processClick mit dem aktuellen Zoom auf. Bei einem Treffer speichert onClick die Attribute für die InfoBubble; andernfalls wird die Auswahl aufgehoben.