I am trying to show different locations of stores that exists in a database in the based on user search, but at first i need to center the map using user's current latitude and longitude.
I did set the lat and lng to 0 in the state and updated the state values when the component is mounted.
The problem is, the map component does not re-render when this state value is updated.
import React, { Component } from 'react'
import { Map, GoogleApiWrapper, InfoWindow, Marker } from 'google-maps-react';
import { GeneConsumer } from '../../store';
const mapStyles = {
width: '100% !important',
height: '100% !important'
};
class LocationMap extends Component {
constructor(props) {
super(props);
this.state = {
currentLatLng: {
lat: 0,
lng: 0
},
showingInfoWindow: false, //Hides or the shows the infoWindow
activeMarker: {}, //Shows the active marker upon click
selectedPlace: {} //Shows the infoWindow to the selected place upon a marker
}
}
componentDidMount() {
navigator.geolocation.getCurrentPosition(
(position) => {
this.setState({
currentLatLng: {
lat: position.coords.latitude,
lng: position.coords.longitude
}
});
},
(error) => {
this.setState({
currentLatLng: {
lat: 6.4494007,
lng: 3.4498444
}
});
}
)
}
render() {
console.log(this.state.currentLatLng.lat)
console.log(this.state.currentLatLng.lng)
return(
<GeneConsumer>
{value => {
const {locations} = value;
const displayMarkers = () => {
if(!locations){
return null;
}
return locations.map((location, index) => {
return <Marker key={index} id={index} position={{
lat: location.latitude,
lng: location.longitude
}}
onClick={() => onMarkerClick(location)}
name = {location.name}
/>
})
}
const onMarkerClick = (props, marker, e) =>
this.setState({
selectedPlace: props,
activeMarker: marker,
showingInfoWindow: true
});
const onClose = props => {
if (this.state.showingInfoWindow) {
this.setState({
showingInfoWindow: false,
activeMarker: null
});
}
};
return (
<Map
google={this.props.google}
zoom={10}
style={mapStyles}
initialCenter={{ lat: this.state.currentLatLng.lat, lng: this.state.currentLatLng.lng}}
>
{displayMarkers()}
<InfoWindow
marker={this.state.activeMarker}
visible={this.state.showingInfoWindow}
onClose={onClose()}
>
<div>
<h4>{this.state.selectedPlace.name}</h4>
</div>
</InfoWindow>
</Map>
);
}}
</GeneConsumer>
);
}
}
export default GoogleApiWrapper({
apiKey: 'xxxxxxxxxxxxxxxxxxxxxxxxxx'
})(LocationMap);