I would like to have an info window open by default above a marker in a google maps component in my react project.
I have tried to accomplish this by having a ref for the marker component, the handler for which calls the marker onclick method which triggers the info window toggle.
However, I am finding that state is not updating despite my call to setState. I have tried doing this in componentDidMount and have also tried setting state directly in the marker mounting handler.
State is mutated successfully if clicking on the marker manually.
I saw this solution but it is a little inelegant as far as using it within react goes and I am frustrated in that I don't see any problems with my logic. It should work and I'd like to know why it doesn't.
Any help would be greatly appreciated - my code is below:
import { Component } from 'react';
import {Map, InfoWindow, Marker, GoogleApiWrapper} from 'google-maps-react';
const style = {
height:'400px',
width: '100%'
}
class MapView extends Component {
constructor() {
super();
this.state = {
showingInfoWindow: true,
activeMarker: {},
selectedPlace: {}
};
}
onMarkerClick = (props, marker, e) => {
this.setState(prevState => ({
selectedPlace: props,
activeMarker: marker,
showingInfoWindow: true
}));
}
onMarkerMounted = element => this.onMarkerClick(element.props, element.marker, element);
onClose = () => {
if (this.state.showingInfoWindow) {
this.setState({
showingInfoWindow: false,
activeMarker: null
});
}
};
render() {
return(
<Map
google={this.props.google}
style={style}
initialCenter={{
lat: {redacted},
lng: {redacted}
}}
zoom={15}
onClick={this.onMapClicked}
>
<Marker ref={this.onMarkerMounted} onClick={this.onMarkerClick}/>
<InfoWindow
marker={this.state.activeMarker}
visible={this.state.showingInfoWindow}
onClose={this.onClose}
>
<div>
Your Location Here!
</div>
</InfoWindow>
</Map>
);
}
}
export default GoogleApiWrapper({
apiKey: ('MY_API_KEY')
})(MapView);