简体   繁体   中英

Using react hooks and google maps api How to show one directions with waypoints and single different marker on same map?

Using react hooks and google maps API I have a code that puts a marker on the map but I don't know add show directions in this code. I searched but couldn't find a map example that includes both and also there is no definite google maps documentation for react hooks. I believe many other people are wondering this too, adding a marker and directions same map in react. I don't want to ask nonspecific questions but I have to. Thank you in advance

My goal is that the map component shows the location as a marker but I have directions too.

Only pins marker working code HERE

Here is my map component I've tried to implement directions but not worked.

MapTest.js

import { Fragment, useEffect, useState, useRef } from 'react';
import { useGoogleMaps } from 'react-hook-google-maps';
import {
  withGoogleMap,
  withScriptjs,
  GoogleMap,
  DirectionsRenderer,
} from 'react-google-maps';

const directions = [
  {
    lat: 35,
    lng: -100,
  },
  {
    lat: 36,
    lng: -100,
  },
];
const MapTest = () => {
  const prevMarkersRef = useRef([]);
  const [directions, setDirections] = useState('');

  // incoming location to set
  let point = {
    lat: 34,
    lng: -100,
  };
  // Map options
  const { ref, map, google } = useGoogleMaps(
    'YOUR API KEY',
    {
      zoom: 8,
      center: point,
    },
    <DirectionsRenderer directions={directions} />
  );
  // directions
  if (map) {
    const directionsService = new google.maps.DirectionsService();
    const origin = {
      lat: 35,
      lng: -100,
    };
    const destination = origin;
    directionsService.route(
      {
        origin: origin,
        destination: point,
        travelMode: google.maps.TravelMode.DRIVING,
        waypoints: directions,
      },
      (result, status) => {
        if (status === google.maps.DirectionsStatus.OK) {
          console.log(result);
          setDirections(result);
        } else {
          console.error(`error fetching directions ${result}`);
        }
      }
    );
  }

  useEffect(() => {
    if (map) {
      // ADD MARKER
      const m = addMarker();
      clearMarkers(prevMarkersRef.current); //clear prev markers
      prevMarkersRef.current.push(m);
      map.setCenter(point);
    }
  }, [point]);

  // SIDE FUNCTIONS
  function addMarker() {
    return new window.google.maps.Marker({
      position: point,
      map: map,
    });
  }
  function clearMarkers(markers) {
    for (let m of markers) {
      m.setMap(null);
    }
  }

  return (
    <div>
      <div
        ref={ref}
        style={{ width: 400, height: 300 }}
      />
    </div>
  );
};

export default MapTest;

You can use the google.maps.DirectionsService() to call the Google Maps Directions API and google.maps.DirectionsRenderer() to display the directions to the map. You can instantiate them inside of your useEffect, bind the DirectionsRenderer to your map using setMap() then pass them in the function calcRoute(directionsService, directionsRenderer)` that will call the DirectionService:

  useEffect(() => {
    if (map) {
      // ADD MARKER
      const m = addMarker();
      clearMarkers(prevMarkersRef.current); //clear prev markers
      prevMarkersRef.current.push(m);
      map.setCenter(point);
      let directionsService = new google.maps.DirectionsService();
      let directionsRenderer = new google.maps.DirectionsRenderer();
      directionsRenderer.setMap(map);
      calcRoute(directionsService, directionsRenderer);
    }
  }, [point]);

For the calcRoute function, build the directions request by setting your origin, destination, mode and other parameters. Then pass them to the directionService.route to send the request. If the DirectionService result status is OK, show your result via the DirectionsRenderer:

function calcRoute(directionsService, directionsRenderer) {
    let request = {
      origin: point,
      destination: dest,
      travelMode: "DRIVING"
    };
    directionsService.route(request, function(result, status) {
      if (status == "OK") {
        directionsRenderer.setDirections(result);
      }
    });
  }

Here is a sample working code .

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