MapConductor React SDK Samples

Imagen sobre el terreno | MapLibre | MapConductor React SDK

Ejemplo de Imagen sobre el terreno de MapConductor React SDK con MapLibre.

Este ejemplo interactivo muestra Imagen sobre el terreno mediante la abstracción de MapConductor sobre MapLibre.

Ejemplo de código

import { useMemo, useState } from 'react';
import {
  createGeoPoint,
  createGeoRectBounds,
  createGroundImageState,
  createMapCameraPosition,
  createMarkerState,
  type MarkerState,
} from '@mapconductor/js-sdk-core';
import { GroundImage, Markers } from '@mapconductor/js-sdk-react';
import { MapLibreDesign, MapLibreMapView2D, useMapLibreViewState } from '@mapconductor/react-for-maplibre';
import '@mapconductor/react-for-maplibre/style.css';


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


  const initialCamera = createMapCameraPosition({
    position: createGeoPoint({ latitude: -26.479235, longitude: 31.306239 }),
    zoom: 15,
  });


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


  // (2) Preparar los datos y el estado de interacción
  // Generate a PNG: MapLibre's image decoder cannot read SVG sources.
  // In your app this can instead be a URL to a PNG or JPEG image.
  const imageUrl = useMemo(() => {
    const canvas = document.createElement('canvas');
    canvas.width = 400;
    canvas.height = 300;
    const context = canvas.getContext('2d')!;
    context.fillStyle = '#bfdbfe';
    context.fillRect(0, 0, 400, 300);
    context.fillStyle = '#2563eb';
    context.fillRect(196, 0, 8, 300);
    context.fillRect(0, 146, 400, 8);
    context.font = '24px sans-serif';
    context.fillText('Ground image', 20, 40);
    return canvas.toDataURL('image/png');
  }, []);
  const initialBounds = createGeoRectBounds({
    southWest: createGeoPoint({ latitude: -26.4849, longitude: 31.2996 }),
    northEast: createGeoPoint({ latitude: -26.4736, longitude: 31.3129 }),
  });
  const [groundImageState] = useState(() => createGroundImageState({
    id: 'historic-map', imageUrl, bounds: initialBounds, opacity: 0.7,
  }));


  const moveSouthWest = (markerState: MarkerState) => {
    groundImageState.bounds = createGeoRectBounds({
      southWest: markerState.position,
      northEast: groundImageState.bounds.northEast,
    });
  };


  const moveNorthEast = (markerState: MarkerState) => {
    groundImageState.bounds = createGeoRectBounds({
      southWest: groundImageState.bounds.southWest,
      northEast: markerState.position,
    });
  };
  const cornerMarkers = useMemo(() => [createMarkerState({
    id: 'south-west', position: groundImageState.bounds.southWest!,
    draggable: true, onDrag: moveSouthWest, onDragEnd: moveSouthWest,
  }), createMarkerState({
    id: 'north-east', position: groundImageState.bounds.northEast!,
    draggable: true, onDrag: moveNorthEast, onDragEnd: moveNorthEast,
  })], [groundImageState]);


  // (3) Renderizar el mapa y sus capas


  return (
    <div style={{ height: 500, position: 'relative', display: 'flex', flexDirection: 'column' }}>
      <MapLibreMapView2D state={mapViewState}>
        <GroundImage state={groundImageState} />
        <Markers states={cornerMarkers} />
      </MapLibreMapView2D>
    </div>
  );
}

Cómo funciona el código

Conserva una instancia de GroundImageState y actualiza sus límites desde marcadores de esquina arrastrables.

Se crea un único GroundImageState con useState y nunca se reemplaza; arrastrar una esquina llama a moveSouthWest, que asigna un createGeoRectBounds nuevo a groundImageState.bounds.

Como el estado es observable, cada asignación de límites se envía al proveedor del mapa, por lo que la imagen superpuesta se estira para seguir a los marcadores de esquina.