Reputation: 304
I'm working on a React application that uses Leaflet
and react-leaflet
to display a map.
I want to create boundaries around cities that are marked on the map with a marker. To get the necessary information for creating these boundaries, I'm making requests to the Nominatim API
, which provides a bbox/boundingbox
property for each city.
I've tried using the Polygon
component from react-leaflet
to create these boundaries, but I keep running into an error that says "Cannot read properties of null (reading '0')".
My code:
function MainMap() {
const markers = useSelector((state) => state.data.markers);
const position = [50.450001, 30.52333];
const polygon = [50.4469916,50.4478686,30.5360665,30.537524]
const blackOptions = {color: "black"}
const getCitiesBounds = async(coords)=>{
try {
const res = await fetch(`https://nominatim.openstreetmap.org/reverse?format=json&lat=${coords.lat}&lon=${coords.lng}&accept-language=ua`)
const data = await res.json()
if(data!=null){
console.log(data)
dispatch(setAddress(data));
return data
}
return null
} catch (error) {
console.log(error.message)
}
}
const GetCurrentCoordinates = () => {
useMapEvents({
click(e) {
getCitiesBounds(e.latlng);
},
});
return false;
};
return (
<div className="mainmap">
<MapContainer minZoom={4} center={position} zoom={5} scrollWheelZoom={false} >
<TileLayer
attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<GetCurrentCoordinates />
<Polygon pathOptions={blackOptions} positions={polygon}/>
</MapContainer>
</div>
);
}
And here's an example of what the bbox property looks like for a city:
{
"boundingbox": [
"40.7127281",
"40.9175771",
"-74.0059668",
"-73.828817"
]
}
"bbox": [
26.1156689,
44.4354754,
26.1157689,
44.4355754
],
Below is an example of what I want:
I've looked online for solutions to this issue, but so far I haven't been able to find anything that works. Can someone help me figure out what I'm doing wrong and how to create these city boundaries correctly? Any help would be greatly appreciated. Thanks in advance!
Upvotes: 1
Views: 379