-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMapComponent.jsx
More file actions
68 lines (62 loc) · 1.91 KB
/
MapComponent.jsx
File metadata and controls
68 lines (62 loc) · 1.91 KB
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
68
import React, { useEffect, useState } from "react";
import { MapContainer, TileLayer, Marker, Popup } from "react-leaflet";
import "leaflet/dist/leaflet.css";
const MapComponent = ({ address }) => {
const city = `${address.city}, ${address.state}, ${address.pincode}`;
const [coordinates, setCoordinates] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
useEffect(() => {
let isMounted = true;
const fetchCoordinates = async () => {
try {
const response = await fetch(
`https://nominatim.openstreetmap.org/search?format=json&q=${city}`
);
const data = await response.json();
if (isMounted) {
if (data.length > 0) {
const { lat, lon } = data[0];
setCoordinates([lat, lon]);
setLoading(false);
} else {
setCoordinates([]);
}
}
} catch (error) {
if (isMounted) {
console.error("Error fetching geocoding data:", error);
setError("Error fetching coordinates");
}
}
};
fetchCoordinates();
return () => {
isMounted = false;
};
}, [city]);
return (
<div>
{loading && <p>Loading...</p>}
{error && <p>{error}</p>}
{coordinates.length > 0 && (
<MapContainer
center={coordinates}
zoom={coordinates.length > 0 ? 13 : 1}
style={{ height: "320px", width: "100%" }}
>
<TileLayer
attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
{coordinates.length > 0 && (
<Marker position={coordinates}>
<Popup>{city}</Popup>
</Marker>
)}
</MapContainer>
)}
</div>
);
};
export default MapComponent;