I have two issues, both of which I have managed to get working in another app using plain Leaflet with Vanilla JS/jquery but I am having issues using React Leaflet.
The first is how to obtain a similar result as to calling .getBounds() (finding a bounding box?) so that I can pass these onto .fitBounds.
The second is how to use .fitBounds in React-Leaflet. I've looked pretty extensively and can find similar solutions but not any that seem to work for mine.
I've successfully obtained geoJson objects/coordinates returned from my node.js backend, and they definitely work as I'm managing to create a geoJson layer each time they are received. Any help/ideas massively appreciated!
n.b. I have also seen other examples using the useMap() hook but cannot seem to get this to work...
Thanks in advance.
import React, { createRef } from 'react';
import { MapContainer, TileLayer, GeoJSON } from "react-leaflet";
import axios from 'axios';
import Card1 from '../Card/card';
class MyMap extends React.Component{
constructor(props){
super(props);
this.state = {
location: '',
latitude: 52.5,
longitude: 0.12,
geoJson: null,
}
this.searchLocation = this.searchLocation.bind(this);
this.handleClick = this.handleClick.bind(this);
this.mapRef = createRef();
}
searchLocation = async (location) => {
this.setState({
location: location})
const response = await axios.get('http://localhost:5000/location', { params: {location} })
if (response.status !== 200){
throw Error(response.message)
} else {
this.setState({ geoJson: response.data.geoJson, key: response.data.key })
}
}
countryStyle = {
fillColor: 'red'
};
render(){
const ReturnGeoJson = () => {
//DOES NOT WORK
// let map = this.mapRef
// // const layer = customAreaRef.current.leafletElement
// if(this.state.geoJson){
// let bounds = this.state.geoJson.getBounds();
// map.fitBounds(bounds, {
// animate: true
// })
// }
return this.state.geoJson && (
<GeoJSON data={this.state.geoJson} key={this.state.key}
/>
)
}
return(
<div>
<MapContainer zoomControl={false} center={[this.state.latitude, this.state.longitude]} zoom={5.5}>
<Card1 searchLocation={this.searchLocation} location={this.state.location}/>
<TileLayer
url="<MAP URL GOES HERE>"
attribution='<MAP ATTR GOES HERE>'
/>
{ReturnGeoJson()}
</MapContainer>
</div>
)
}
}
export default MyMap;