Search code examples
google-maps-api-3react-google-maps

adding waypoints in the react-google-maps


editable samplecode how to use waypoints in the following code does the waypoints helps to plot the way which I updated in the database wheather the ponits will be based on the points I have updated

const DirectionsService = new google.maps.DirectionsService();
                 const  DirectionsDisplay = new google.maps.DirectionsRenderer({suppressMarkers: true},{strokeColor:"#4a4a4a"});

      DirectionsService.route({

        origin: new google.maps.LatLng(this.state.orgin.latitude ,this.state.orgin.longitude),
         destination: new google.maps.LatLng(this.state.destination.latitude ,this.state.destination.longitude),
          travelMode: google.maps.TravelMode.DRIVING,

      }, 
       (result, status) => {
        if (status === google.maps.DirectionsStatus.OK) {
          this.setState({
            directions: result,
          });
        } else {
          console.error(`error fetching directions ${result}`);
        }
      });

            }).catch(function (err) {

            });

    }

  })

)(props =>
  <GoogleMap
    defaultZoom={50}>
     <DirectionsRenderer directions={props.directions}   />

  < Marker

  position={{  lat:props.delivery!=undefined?props.delivery.latitude:null, lng:  props.delivery!=undefined?props.delivery.longitude:null }} />

  </GoogleMap>

);
    return (
      <MapWithADirectionsRenderer />
    )
  }

Solution

  • You can add waypoints by adding waypoints[] array of DirectionsWaypoint in your Directions Request.

    You can check this documentation to learn more: https://developers.google.com/maps/documentation/javascript/directions#DirectionsRequests

    Here's a sample waypoints array:

    waypoints: [
        {
            location: new google.maps.LatLng(14.546748, 121.05455)
        },
        {
            location: new google.maps.LatLng(14.552444,121.044488)
        }
    ]
    

    Here's a sample Direction Request with waypoints:

    DirectionsService.route({
       origin: new google.maps.LatLng(14.533593, 121.053128),
       destination: new google.maps.LatLng(14.550895, 121.025079),
       travelMode: google.maps.TravelMode.DRIVING,
       waypoints: [
            {
               location: new google.maps.LatLng(14.546748, 121.05455)
            },
            {
               location: new google.maps.LatLng(14.552444,121.044488)
            }
       ]
    }, (result, status) => {
       if (status === google.maps.DirectionsStatus.OK) {
          this.setState({
             directions: result,
          });
       } else {
         console.error(`error fetching directions ${result}`);
       }
    });