Ejemplo de código
import { useEffect, useMemo, useState } from 'react';
import {
RasterLayerSource,
createGeoPoint,
createMapCameraPosition,
createRasterLayerState,
} from '@mapconductor/js-sdk-core';
import { RasterLayer } 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: 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 [opacity, setOpacity] = useState(0.75);
const tileSource = useMemo(() => RasterLayerSource.UrlTemplate({
template: 'https://cyberjapandata.gsi.go.jp/xyz/std/{z}/{x}/{y}.png',
tileSize: 256,
}), []);
const layer = useMemo(() => createRasterLayerState({
source: tileSource,
opacity: 0.75,
}), [tileSource]);
useEffect(() => { layer.opacity = opacity; }, [layer, opacity]);
// (3) Renderizar el mapa y sus capas
return (
<div style={{ height: 500, position: 'relative', display: 'flex', flexDirection: 'column' }}>
<input aria-label="Opacity" type="range" min="0" max="1" step="0.05"
value={opacity} onChange={event => setOpacity(Number(event.target.value))} />
<MapLibreMapView2D state={mapViewState}>
<RasterLayer state={layer} />
</MapLibreMapView2D>
</div>
);
}
Cómo funciona el código
Agrega una fuente ráster en mosaicos mediante el estado compartido de la capa y cambia su opacidad sin recrear el mapa.
El tileSource es un RasterLayerSource.UrlTemplate que apunta a una URL de mosaicos {z}/{x}/{y}, mientras que opacity se guarda en el estado de React.
createRasterLayerState envuelve ambos valores, y cambiar opacity actualiza la RasterLayer existente en el sitio en lugar de reconstruir el mapa.