Estoy tratando de obtener las coordenadas de dónde hace clic el mouse en el mapa, pero .locate() solo devuelve las coordenadas centrales del mapa. ¿Hay alguna manera? PD. No estoy usando una reacción basada en clases. Gracias
<MapContainer center={[ 33.8735578, 35.86379]} zoom={9} scrollWheelZoom={true} > <TileLayer attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" /> </MapContainer>puede obtener las coordenadas del clic del mouse mediante el gancho useMapEvents .
prueba este
const MapEvents = () => { useMapEvents({ click(e) { // setState your coords here // coords exist in "e.latlng.lat" and "e.latlng.lng" console.log(e.latlng.lat); console.log(e.latlng.lng); }, }); return false; } return ( <MapContainer center={[ 33.8735578, 35.86379]} zoom={9} scrollWheelZoom={true} > <TileLayer attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" /> <MapEvents /> </MapContainer> )Pregunta y donde esta tu codigo? No eres nuevo en este sitio, por lo que debes saber mostrar lo que has hecho hasta ahora. De acuerdo, seré amable hoy ;) No quiero cortar y limpiar el código, así que lo pego como está.
import { useEffect } from 'react'; import { MapContainer, useMap, TileLayer, } from 'react-leaflet'; import L from 'leaflet'; import tileLayer from '../util/tileLayer'; const center = [52.22977, 21.01178]; const GetCoordinates = () => { const map = useMap(); useEffect(() => { if (!map) return; const info = L.DomUtil.create('div', 'legend'); const positon = L.Control.extend({ options: { position: 'bottomleft' }, onAdd: function () { info.textContent = 'Click on map'; return info; } }) map.on('click', (e) => { info.textContent = e.latlng; }) map.addControl(new positon()); }, [map]) return null } const MapWrapper = () => { return ( <MapContainer center={center} zoom={18} scrollWheelZoom={false}> <TileLayer {...tileLayer} /> <GetCoordinates /> </MapContainer> ) } export default MapWrapper;