I am using React to render a Leaflet map that is displaying information from an API. I also have a drop-down that has cities that can be selected. When the city is selected, I am passing the prop to the map to display the data. When another city is selected, it won’t rerender the map to the city that is selected. How can I get the map to move to the selected city?
This is the MapDisplay component that is displaying the map and processing the data.
export const MapDisplay = ({ city }) => {
// const [userInput, setInput] = useState({
// city: city
// })
const [isLoading, setIsLoading] = useState(true)
const [data, setData] = useState([])
const [initialCoords, setCoords] = useState({
lat: null,
long: null
})
useEffect(() => {
async function fetchData(){
getData(city)
}
fetchData()
}, [city])
const getData = async (city) => {
try {
const myData = await citySearch(city)
setData(myData.data)
setCoords({
lat: myData.data[0].geometry.coordinates[1].toFixed(3),
long: myData.data[0].geometry.coordinates[0].toFixed(3)
})
setIsLoading(false)
} catch (error) {
console.log(`> Error: ${error}`)
}
}
console.log(`City: ${city} Lat: ${initialCoords.lat}, Long: ${initialCoords.long}`)
const position = [initialCoords.lat, initialCoords.long]
return typeof data === "string" ? `No Current Information for ${city}`: isLoading ?
(
<Fragment>
<Loader />
</Fragment>
):
(
<Fragment>
<Map
city={city}
position={position}
data={data}
/>
</Fragment>
)
}
This is the map Component
export const Map = ({ city, data, position }) => {
const markerIcon = divIcon({
className: "icon",
html: renderToStaticMarkup(<i className={"fas fa-map-pin"}></i>)
})
return (
<Fragment>
<div>
<h4>Currently searching area around { city }</h4>
</div>
<MapContainer center={position} zoom={9} scrollWheelZoom={false}>
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
{
data.map(item => (
<Marker
key={item.id}
position={[item.geometry.coordinates[1], item.geometry.coordinates[0] ]}
icon={markerIcon}
>
<Popup >
<div>
<p>Location: {item.properties.place}</p>
<p>Magnitude: {item.mag}</p>
</div>
</Popup>
</Marker>
))
}
</MapContainer>
</Fragment>
)
}