I have a problem with Google Map in React. Everything works great but, when I try to re-render other place in this map it doesnt work :( I mean when I change city (e.g. select) new props (latitude, longitude) are used , but city one the map not change
import React from 'react';
import ReactDOM from 'react-dom';
import { withGoogleMap, GoogleMap, Marker } from "react-google-maps";
const SimpleMapExampleGoogleMap = withGoogleMap( props => {
console.log("here new props are used", props)
return <GoogleMap
defaultZoom={15}
defaultCenter={new google.maps.LatLng(props.lat, props.lng)}
/>
}
);
class GMap extends React.Component{
constructor(props) {
super(props);
this.state = {
lat: this.props.lat,
lng: this.props.lng
}
}
render() {
console.log("New props ", this.props)
return <SimpleMapExampleGoogleMap
lat={this.props.lat}
lng={this.props.lng}
containerElement={
<div style={{ height: `500px` }} />
}
mapElement={
<div style={{ height: `500px` }} />
}
/>
}
}
export { GMap }
You have set state for lng and lat but you didn't apply them on the map
=> change this.props.lat to this.state.lat, and same for the lng:
return <SimpleMapExampleGoogleMap
lat={this.state.lat}
lng={this.state.lng}
containerElement={
<div style={{ height: `500px` }} />
}
mapElement={
<div style={{ height: `500px` }} />
}
/>
If the above code doesn't update your map yet, then feel free to add the following method (same level as constructors):
constructors(props){/*...*/}
componentWillReceiveProps(nextProps) {
this.setState({
lat: nextProps.lat,
lng: nextProps.lng,
});
}
render(){/*...*/}
Please also post here if you have errors, thanks
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With