I am using library react-google-maps, and i want to use DirectionsRenderer between two nodes. Here is my state
this.state={
currentPosition:{lat: 26.84 ,lng: 75.80},
destinationPosition:{lat: 26.84 ,lng: 75.80},
};
I want to show the direction between my current location and marker. And my componentDidMount() is inside render method. Here is the code for render method
class map extends React.PureComponent{
constructor(props){
super(props);
this.state={
currentPosition:{lat: 26.84 ,lng: 75.80},
destinationPosition:{lat: 26.84 ,lng: 75.80},
direction:false
};
}
onMarkerPositionChanged(e){
this.setState((state)=>({
destinationPosition:{lat:e.latLng.lat(),lng:e.latLng.lng()}}));
}
handleClick(){
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition((position)=>{
this.setState(()=>({
currentPosition:{lat:position.coords.latitude,lng:position.coords.longitude}}))
});
}
else{
alert("Geoloaction is not supported by your browser");
}
}
changeDir(){
if(this.state.direction)
this.setState(()=>({direction:false}))
else
this.setState(()=>({direction:true}))
}
render(){
const MyMapComponent = compose(
withProps({
googleMapURL: "https://maps.googleapis.com/maps/api/js?key=AIzaSyC5VMMlyr_A6K5ycpOrq3OsVM8YYbn0q3A&v=3.exp&libraries=geometry,drawing,places",
loadingElement: <div style={{ height: `100%` }} />,
containerElement: <div style={{ height: `300px` }} />,
mapElement: <div style={{ height: `100%` }} />,
}),
withScriptjs,
withGoogleMap,
lifecycle({
componentDidMount() {
const google=window.google;
console.log(this.state);
//--->this statement prints null
const DirectionsService = new google.maps.DirectionsService();
DirectionsService.route({
origin: new google.maps.LatLng(this.state.currentPosition.lat, this.state.currentPosition.lng),
destination: new google.maps.LatLng(this.state.destinationPosition.lat,this.state.destinationPosition.lng),
//----> this is where i want to use the state to get the direction between //current location and marker
travelMode: google.maps.TravelMode.DRIVING,
}, (result, status) => {
if (status === google.maps.DirectionsStatus.OK) {
this.setState({
directions: result,
});
} else {
console.error(`error fetching directions ${result}`);
}
});
}
})
)(
props =>
<GoogleMap defaultZoom={15} defaultCenter={this.state.destinationPosition} >
<Marker position={this.state.destinationPosition} draggable changeLat
onDragEnd={this.onMarkerPositionChanged.bind(this)}
/>
<Marker
icon="https://www.robotwoods.com/dev/misc/bluecircle.png"
position={this.state.currentPosition}
/>
{this.state.direction && props.directions && <DirectionsRenderer directions={props.directions} />}
<Button bsStyle="success" onClick={this.handleClick.bind(this)}>Current Position</Button>
<Button bsStyle="success" onClick={this.changeDir.bind(this)}>Get Direction</Button>
</GoogleMap>
);
return(
<Container state={this.state} map={MyMapComponent}/>
);
}
}
export default map;
when i use constant numbers in place of origin and destination it works fine.