简体   繁体   English

使用反应钩子和谷歌地图 api 如何在同一个 map 上显示一个带有航点和单个不同标记的方向?

[英]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.使用反应挂钩和谷歌地图 API 我有一个代码在 map 上放置一个标记,但我不知道在此代码中添加显示方向。 I searched but couldn't find a map example that includes both and also there is no definite google maps documentation for react hooks.我搜索但找不到包含两者的 map 示例,并且也没有针对反应挂钩的明确谷歌地图文档。 I believe many other people are wondering this too, adding a marker and directions same map in react.我相信许多其他人也想知道这一点,在反应中添加一个标记和方向相同的 map。 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.我的目标是 map 组件将位置显示为标记,但我也有方向。

Only pins marker working code HERE只有引脚标记工作代码在这里

Here is my map component I've tried to implement directions but not worked.这是我的 map 组件,我尝试执行指示但没有成功。

MapTest.js 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.您可以使用google.maps.DirectionsService()调用 Google 地图方向 API 和google.maps.DirectionsRenderer()来显示到 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 中实例化它们,使用setMap() then pass them in the function calcRoute(directionsService,directionsRenderer)`,它将调用 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.对于calcRoute function,通过设置您的起点、目的地、模式和其他参数来构建路线请求 Then pass them to the directionService.route to send the request.然后将它们传递给 directionService.route 以发送请求。 If the DirectionService result status is OK, show your result via the DirectionsRenderer:如果 DirectionService 结果状态为 OK,则通过 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 .这是一个示例工作代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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