Nr Ri
Nr Ri

Reputation: 41

REACT how can i draw a route with google-map-react?

how can i draw a route with npm google-map-react ?

this is what i have

this.map = (zoom, lat, lng) => { let DirectionsService = new window.google.maps.DirectionsService();

  DirectionsService.route(
    {
      origin: new window.google.maps.LatLng(40.407749, -3.710138), //
      destination: new window.google.maps.LatLng(40.762341, -3.788512), //
      travelmode: window.google.maps.TravelMode.DRIVING
    },
    (result, status) => {
      if (status === window.google.maps.DirectionsStatus.OK) {
        this.setState({
          direction: result
        });
      } else {
        console.error(`error fetching directions ${result}`);
      }
    }
  );

Upvotes: 4

Views: 6377

Answers (1)

Pagemag
Pagemag

Reputation: 2977

You can do something like this(sample code and code snippet below) wherein you will pass the map object when the API is loaded then use the apiIsLoaded function to call the directions service.

import React, { Component } from "react";
import GoogleMapReact from "google-map-react";
import "./style.css";

class GoogleMaps extends Component {
  constructor(props) {
    super(props);

    this.state = {
      currentLocation: { lat: 40.756795, lng: -73.954298 }
    };
  }

  render() {
    const apiIsLoaded = (map, maps) => {
      const directionsService = new google.maps.DirectionsService();
      const directionsRenderer = new google.maps.DirectionsRenderer();
      directionsRenderer.setMap(map);
      const origin = { lat: 40.756795, lng: -73.954298 };
      const destination = { lat: 41.756795, lng: -78.954298 };

      directionsService.route(
        {
          origin: origin,
          destination: destination,
          travelMode: google.maps.TravelMode.DRIVING
        },
        (result, status) => {
          if (status === google.maps.DirectionsStatus.OK) {
            directionsRenderer.setDirections(result);
          } else {
            console.error(`error fetching directions ${result}`);
          }
        }
      );
    };
    return (
      <div>
        <div style={{ height: "400px", width: "100%" }}>
          <GoogleMapReact
            bootstrapURLKeys={{
              key: "YOUR_API_KEY"
            }}
            defaultCenter={{ lat: 40.756795, lng: -73.954298 }}
            defaultZoom={10}
            center={this.state.currentLocation}
            yesIWantToUseGoogleMapApiInternals
            onGoogleApiLoaded={({ map, maps }) => apiIsLoaded(map, maps)}
          />
        </div>
      </div>
    );
  }
}
export default GoogleMaps;

Upvotes: 4

Related Questions