Search code examples
javascriptreactjsgoogle-maps-api-3create-react-app

google maps api does not provide directions.js dependency for DirectionsService()


I'm trying to use google maps api v3 with react, but it seems that some of the google maps services are not loading when using react. I've tried both lazy loading the script via this tutorial and just loading the script directly in my index.html file, but to no avail. I'm using create-react-app with the following dependencies:

"classnames": "^2.2.5",
"invariant": "^2.2.2",
"node-sass-chokidar": "0.0.3",
"npm-run-all": "^4.1.1",
"prop-types": "^15.5.10",
"react": "^15.6.1",
"react-dom": "^15.6.1",
"react-redux": "^5.0.6",
"react-scripts": "1.0.13",
"redux": "^3.7.2"

If I take the instantiation of the DirectionsService code out of my react application and include the GMAP API the same way I am with React codepen then it seems that all of the google maps dependencies are loading. In fact, if I go as far as to remove any reference to the DirectionsService code from code pen, the directions.js file is still loaded in the network tab.

google map dependencies are loading in code pen

However, with react this is what my network tab looks like:

no directions service

Has anyone ever experienced something like this?


Solution

  • It turns out that the DirectionsService() needs to be instantiated before the map is.

      loadMap(node) {
        if (this.props && this.props.google) {
          const { google } = this.props;
    
          // instantiate Direction Service first
          this.directionsService = new google.maps.DirectionsService();
    
          this.directionsDisplay = new google.maps.DirectionsRenderer({
            suppressMarkers: true,
          });
    
          const zoom = 13;
          const mapTypeId = google.maps.MapTypeId.ROADMAP;
          const lat = 37.776443;
          const lng = -122.451978;
          const center = new google.maps.LatLng(lat, lng);
    
          const mapConfig = Object.assign({}, {
            center,
            zoom,
            mapTypeId,
          });
    
    
          this.map = new google.maps.Map(node, mapConfig);
    
          this.directionsDisplay.setMap(this.map);
    
          // make the map instance available to other components as it is just data
          this.props.dispatchGoogleMap(this.map);
        }
      }