I'm trying to use react-google-maps as an latitude and longitude input in my app. In order to get the position that the user selected I'm using the onclick event and it works almost as expected because the marker is set, but the map is refreshing and going to the default center and zoom when the user selects the desired location. How can I avoid this weird behaviour?
import React from "react";
import { withScriptjs, withGoogleMap, GoogleMap, Marker, MarkerWithLabel } from "react-google-maps";
export default class MapTest extends React.Component {
constructor(){
super();
this.state={
isMarkerShown: false,
markerPosition: null
}
}
onMapClick= (e) => this.setState({
markerPosition: e.latLng,
isMarkerShown:true}
);
render() {
var Map= withScriptjs(withGoogleMap((props) =>
<GoogleMap
defaultZoom={12}
center={ { lat: 4.4360051, lng: -75.2076636 } }
onClick={this.onMapClick}
>
{this.state.isMarkerShown && <Marker position={this.state.markerPosition} />}
</GoogleMap>));
return (<Map {...this.props} />);
}
}
That is because you are creating a new object in each render
call.
the withScriptjs(withGoogleMap
should be stored somewhere an re-used
For example
class MapTest extends React.Component {
//...
Map = withScriptjs(
withGoogleMap(props => (
<GoogleMap
defaultZoom={12}
center={{ lat: 4.4360051, lng: -75.2076636 }}
onClick={props.onClick}
>
{props.children}
</GoogleMap>
))
);
render() {
return <this.Map {...this.props} onClick={this.onMapClick}>
{this.state.isMarkerShown && (
<Marker position={this.state.markerPosition} />
)}
</this.Map>;
}
}