import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import 'leaflet-defaulticon-compatibility/dist/leaflet-defaulticon-compatibility.css';
import 'leaflet-defaulticon-compatibility';
import { useEffect, useRef, useState } from 'react';
const [mapInstance, setMapInstance] = useState<L.Map | null>(null);
const markerRef = useRef<L.Marker | null>(null);
const mapRef = useRef<HTMLDivElement | null>(null);
useEffect(() => {
if (!mapRef.current) return;
const map = L.map(mapRef.current).setView([17.2495995, -62.6965999], 10);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors',
}).addTo(map);
map.on('click', (event: L.LeafletMouseEvent) => {
const { lat, lng } = event.latlng;
if (!markerRef.current) {
const newMarker = L.marker([lat, lng]).addTo(map);
markerRef.current = newMarker;
} else {
markerRef.current.setLatLng([lat, lng]);
}
console.log(`Marker updated to: Lat ${lat}, Lng ${lng}`);
form.setValue('map_lat', lat);
form.setValue('map_lng', lng);
});
setMapInstance(map);
return () => {
map.remove();
};
}, []);
<p className="text-sm mt-2">
Click on the map to place a marker and set the property's location.
</p>
<div ref={mapRef} className="w-full h-96 rounded-md border" />