I've successfully been able to render the Markers for react-google-maps, but when I started trying to use DirectionsRenderer, I ran into this 'google is not defined' issue. I scoured StackOverflow and the web in general for solutions to this, anywhere from declaring 'google' as a global to playing around with the withScriptjs syntax, and nothing has worked. I'm running out of ideas. Sidenote: I'm deliberately avoiding using the 'recompose' library from the docs because even the library's author thinks Hooks are better...so idk, maybe give me a solution that doesn't require 'recompose' if possible? Thanks a million.
Here's my code:
/* global google */
import React, { useState, useEffect } from 'react'
import { withGoogleMap, GoogleMap, Marker, DirectionsRenderer } from 'react-google-maps'
import './App.css'
function MyDirectionsRenderer(props) {
const [directions, setDirections] = useState(null);
const { origin, destination, travelMode } = props;
useEffect(() => {
const directionsService = new google.maps.DirectionsService();
directionsService.route(
{
origin: new google.maps.LatLng(origin.lat, origin.lng),
destination: new google.maps.LatLng(destination.lat, destination.lng),
travelMode: travelMode
},
(result, status) => {
if (status === google.maps.DirectionsStatus.OK) {
setDirections(result);
} else {
console.error(`error fetching directions ${result}`);
}
}
);
}, [directions, destination.lat, destination.lng, origin.lat, origin.lng, travelMode]);
return (
<React.Fragment>
{directions && <DirectionsRenderer directions={directions} />}
</React.Fragment>
);
}
class Map extends React.Component {
constructor(props){
super(props);
this.state = {
directions: null
}
}
render(){
const MyMapComponent = withGoogleMap(props => {
return (
<GoogleMap
defaultZoom={10}
defaultCenter={{ lat: 42.681340, lng: -89.026930 }}
>
<Marker
position = {{lat: 42.681340, lng: -89.026930}}
/>
<MyDirectionsRenderer
origin= {{lat: 42.681339, lng: -89.026932}}
destination= {{lat: 28.250200, lng: -82.714080}}
travelMode= {google.maps.TravelMode.DRIVING}
/>
</GoogleMap>
)
})
return (
<MyMapComponent
loadingElement={<div style={{ height: `100%` }} />}
containerElement={<div style={{ height: `400px` }} />}
mapElement={<div style={{ height: `100%` }} />}
/>
)
}
}
export default Map
Edit: I updated the code here to reflect the current status of the project and any existing problems with it. Currently, the problem is that I can't see the route on my map.