1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
import { createControlComponent } from '@react-leaflet/core';
import { LocateControl as LeafletLocateControl, LocateOptions } from 'leaflet.locatecontrol';
import "leaflet.locatecontrol/dist/L.Control.Locate.min.css";
import { useEffect } from 'react';
import { useMap } from 'react-leaflet';
import { useApp } from '../AppContext';
interface EnhancedLocateControlProps {
options?: LocateOptions;
}
// Componente que usa el contexto para manejar la localización
export const EnhancedLocateControl = (props: EnhancedLocateControlProps) => {
const map = useMap();
const { mapState, setUserLocation, setLocationPermission } = useApp();
useEffect(() => {
// Configuración por defecto del control de localización
const defaultOptions: LocateOptions = {
position: 'topright',
strings: {
title: 'Mostrar mi ubicación',
},
flyTo: true,
onLocationError: (err) => {
console.error('Error en la localización:', err);
setLocationPermission(false);
},
returnToPrevBounds: true,
showPopup: false,
};
// Combinamos las opciones por defecto con las personalizadas
const options = { ...defaultOptions, ...props.options };
// Creamos la instancia del control
const locateControl = new LeafletLocateControl(options);
// Añadimos el control al mapa
locateControl.addTo(map);
// Si tenemos permiso de ubicación y ya conocemos la ubicación del usuario,
// podemos activarla automáticamente
if (mapState.hasLocationPermission && mapState.userLocation) {
// Esperamos a que el mapa esté listo
setTimeout(() => {
try {
locateControl.start();
} catch (e) {
console.error('Error al iniciar la localización automática', e);
}
}, 1000);
}
return () => {
// Limpieza al desmontar el componente
locateControl.remove();
};
}, [map, mapState.hasLocationPermission, mapState.userLocation, props.options, setLocationPermission, setUserLocation]);
return null;
};
// Exportamos también el control base por compatibilidad
export const LocateControl = createControlComponent(
(props) => new LeafletLocateControl(props)
);
|