import React, { useState, useEffect } from 'react';
import { MapContainer, TileLayer, Marker, useMapEvents } from 'react-leaflet';
import 'leaflet/dist/leaflet.css';
import L from 'leaflet';
// Fix for default marker icon
delete L.Icon.Default.prototype._getIconUrl;
L.Icon.Default.mergeOptions({
iconRetinaUrl: 'https://unpkg.com/leaflet@1.7.1/dist/images/marker-icon-2x.png',
iconUrl: 'https://unpkg.com/leaflet@1.7.1/dist/images/marker-icon.png',
shadowUrl: 'https://unpkg.com/leaflet@1.7.1/dist/images/marker-shadow.png',
});
const LocationPicker = ({ onLocationSelect }) => {
// Default to Kerala's approximate center (Thrissur)
const KERALA_CENTER = { lat: 10.5276, lng: 76.2144 };
const [position, setPosition] = useState(KERALA_CENTER);
const [address, setAddress] = useState('');
const [searchQuery, setSearchQuery] = useState('');
// Custom component to handle map clicks and location selection
function LocationMarker() {
const map = useMapEvents({
click(e) {
const { lat, lng } = e.latlng;
setPosition(e.latlng);
// Reverse geocoding to get address details
fetch(`https://nominatim.openstreetmap.org/reverse?format=json&lat=${lat}&lon=${lng}&zoom=18&addressdetails=1`)
.then(response => response.json())
.then(data => {
const fullAddress = data.display_name || 'Address not found';
setAddress(fullAddress);
// Optional: Pass location details back to parent component
onLocationSelect && onLocationSelect({
lat,
lng,
address: fullAddress
});
})
.catch(error => console.error('Error fetching location details:', error));
},
});
return position === null ? null : (
Selected Location:
{address}