简体   繁体   中英

React-google-maps render directions

I am working with the react-google-maps package https://github.com/tomchentw/react-google-maps to make a request to the google maps javascript API directions service https://developers.google.com/maps/documentation/javascript/examples/directions-simple . I am getting the response back from the API as expected and can log it to the browser but I can not figure out how to get the polyline to render in the map component.

This line of code directionsDisplay.setMap(map); was returning an error of

"InvalidValueError: setMap: not an instance of Map directions".

So I commented it out because it seems that the map is set by passing the handleMapLoad() to the GoogleMap component through refs. Some guidance on how to display the polyline would be much appreciated.

    /*global google*/
    import React, { Component } from "react";
    import { withGoogleMap, GoogleMap } from "react-google-maps";

    const GettingStartedGoogleMap = withGoogleMap(props => (
      <GoogleMap
        ref={props.onMapLoad}
        defaultZoom={5}
        defaultCenter={{lat: 41.85, lng: -117.65}}
      >
      </GoogleMap>
    ));

    export default class GettingStartedExample extends Component {
      handleMapLoad = this.handleMapLoad.bind(this);

      handleMapLoad(map) {
        this.mapComponent = map;
        if (map) {
          console.log(map.getZoom());
        }
        const directionsService = new google.maps.DirectionsService();
        const directionsDisplay = new google.maps.DirectionsRenderer(); 

        // directionsDisplay.setMap(map);

        const makeRequest = function() {
          calculateAndDisplayRoute(directionsService, directionsDisplay);
        };
        function calculateAndDisplayRoute(directionsService, directionsDisplay) {
           directionsService.route({
             origin: 'San Francisco',
             destination: 'Portland',
             travelMode: 'DRIVING'
          }, function(response, status) {
            if (status === 'OK') {
              directionsDisplay.setDirections(response);
              console.log(response)
            } else {
              window.alert('Directions request failed due to ' + status);
            }
          });
        }
        makeRequest();
      }
      render() {
        return (
          <div style={{height: `500px`}}>
            <GettingStartedGoogleMap
              containerElement={<div style={{ height: `100%` }} />}
              mapElement={<div style={{ height: `100%` }} />}
              onMapLoad={this.handleMapLoad}
            />
          </div>
         );
       }
     }

You can use react-google-maps Polyline component to render direction. It gives us additional styling prop options . It is a way better approach than using the DirectionRender component. Here are the steps you must follow to render directions as Polyline on your Google Map:

  • Use google maps direction service and extract overview_path from it like this; overview_path is an array of objects containing Lat and Lng .

...

DirectionsService.route({   
   origin: 'San Francisco', 
   destination: 'Portland',   
   travelMode: google.maps.TravelMode.DRIVING,   
  },  
    (result, status) => {   
      if (status === google.maps.DirectionsStatus.OK) {   
        const overViewCoords = result.routes[0].overview_path;   
          this.setState({   
            lineCoordinates: overViewCoords,
          });
      } else {
         console.warn(`error fetching directions ${status}`);
      }
    });
  • Then pass these coordinates as the path prop of the <Polyline /> Component;

...

<GoogleMap
    ref={props.onMapLoad}
    defaultZoom={5}
    defaultCenter={{lat: 41.85, lng: -117.65}}
  >
  <Polyline
        path={this.state.lineCoordinates}
        geodesic={false}
        options={{
            strokeColor: '#38B44F',
            strokeOpacity: 1,
            strokeWeight: 7,
        }}
    />
</GoogleMap>

PS. import Polyline from react-google-maps first:

import { Polyline } from 'react-google-maps';

A very simple and direct way to render directions in React using waypoints too

import React from 'react';
import logo from './logo.svg';
import './App.css';
import { withScriptjs } from "react-google-maps";




import  Map from './components/Map';

function App() {

  const MapLoader = withScriptjs(Map);

  return (

<div className="App">
  <header className="App-header">
    <img src={logo} className="App-logo" alt="logo" />

  </header>
  <MapLoader
      googleMapURL="https://maps.googleapis.com/maps/api/js?key=Key"
      loadingElement={<div style={{ height: `100%` }} />}
  />
</div>
  );
}

export default App;

And in your Map.js file

/*global google*/
import React, { Component } from "react";
import {
    withGoogleMap,
    withScriptjs,
    GoogleMap,
    DirectionsRenderer
} from "react-google-maps";
class Map extends Component {
    state = {
        directions: null,


};

componentDidMount() {
    const directionsService = new google.maps.DirectionsService();

    const origin = { lat: 6.5244, lng:  3.3792 };
    const destination = { lat: 6.4667, lng:  3.4500};

    directionsService.route(
        {
            origin: origin,
            destination: destination,
            travelMode: google.maps.TravelMode.DRIVING,
            waypoints: [
                {
                    location: new google.maps.LatLng(6.4698,  3.5852)
                },
                {
                    location: new google.maps.LatLng(6.6018,3.3515)
                }
            ]
        },
        (result, status) => {
            if (status === google.maps.DirectionsStatus.OK) {
                console.log(result)
                this.setState({
                    directions: result
                });
            } else {
                console.error(`error fetching directions ${result}`);
            }
        }
    );
}

render() {
    const GoogleMapExample = withGoogleMap(props => (
        <GoogleMap
            defaultCenter={{ lat: 6.5244, lng:  3.3792 }}
            defaultZoom={13}
        >
            <DirectionsRenderer
                directions={this.state.directions}
            />
        </GoogleMap>
    ));

    return (
        <div>
            <GoogleMapExample
                containerElement={<div style={{ height: `500px`, width: "500px" }} />}
                mapElement={<div style={{ height: `100%` }} />}
            />
        </div>


       );
    }
}

export default Map;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM