【问题标题】:react and google Directions API without map没有地图的反应和谷歌方向API
【发布时间】:2020-10-29 07:33:31
【问题描述】:

我需要在我的内部应用程序中来自.route() 的结果,而不是进入任何地图。我需要起点和终点之间的持续时间和距离,以便在我的应用中进行进一步计算。

到目前为止,我尝试了一个回调函数:

function getTravelTime(origin, destination, cb) {
    const directionsService = new google.maps.DirectionsService();
    directionsService.route(
        {
            origin: origin,
            destination: destination,
            travelMode: "DRIVING"
        },
        (result, status) => {
            if (status === google.maps.DirectionsStatus.OK) {
                cb(null, {
                    duration: moment.utc(moment.duration(result.routes[0].legs[0].duration.value, 'seconds').as('milliseconds')).format('HH:mm'),
                    distance: result.routes[0].legs[0].distance.value
                });
            } else {
                cb('error');
                console.log(result);
            }
        }
    );
};

我试着这样读:

let tInfo = getTravelTime(origin, destination, function (err, dist) {
   if (!err) {
      let distanceBetweenLocations = dist.distance;
      let durationBetweenLocations = dist.duration;
      // Or with saving to a state
      setTravelInformation(prevState => ({
         distance: dist.distance,
         duration: dist.duration
      }));
    }
});  

有没有可能在不需要渲染地图的情况下计算距离和旅行时间?

到目前为止,我得到了这个,大大缩短了,因为我在同一个文件中获得了更多其他组件的逻辑:

import {
withGoogleMap,
GoogleMap,
withScriptjs,
Marker,
DirectionsRenderer
} from "react-google-maps";

const getTravelTime = (origin, destination) => {
    const directionsService = new google.maps.DirectionsService();
    directionsService.route(
      {
        origin: origin,
        destination: destination,
        travelMode: google.maps.TravelMode.DRIVING
      },
      (result, status) => {
        console.log(result)
        if (status === google.maps.DirectionsStatus.OK) {
          setDirections(result);
        } else {
          setError(result);
        }
      }
    );
}  

我是否需要将 HoC 与 Scriptjs 一起使用并围绕它包装我的组件?

【问题讨论】:

  • 您在地图上的哪个位置呈现这些方向?发布的代码没有显示。什么不起作用?你的问题既不清楚又太宽泛。请提供minimal reproducible example 以及清晰的问题描述。
  • 我为我的问题添加了一个编辑。路线计算有效,但由于它是异步的,我无法读取数据,我需要结果以在我的应用程序中进行进一步的内部计算。我用回调函数试过了,但还是不行。

标签: reactjs google-maps google-directions-api travel-time


【解决方案1】:

你可以使用useStateuseEffect,见https://reactjs.org/docs/hooks-effect.html

const [distance, setDistance] = useState(0);
const [duration, setDuration] = useState(0);

useEffect(() => {
  if (distance && duration) {
    console.log("Distance & Duration have updated", distance, duration);
  }
}, [distance, duration]);

当您收到路线结果时,使用您需要的任何值更新距离和持续时间:

directionsService.route({
    origin: origin,
    destination: destination,
    travelMode: google.maps.TravelMode.DRIVING
  },
  (result, status) => {
    if (status === google.maps.DirectionsStatus.OK) {
      setDistance(result.routes[0].legs[0].distance.value);
      setDuration(result.routes[0].legs[0].duration.value);
    } else {
      console.error("error fetching directions", result, status);
    }
  }
);

这是一个使用 @react-google-maps/api 的工作 sn-p

https://codesandbox.io/s/react-google-mapsapi-directions-service-m7qif

您需要使用有效的 API 密钥以防它不起作用。

【讨论】:

    【解决方案2】:
        import React, { Component } from "react";
        import { withGoogleMap, GoogleMap, withScriptjs, DirectionsRenderer, Marker } from "react-google-maps";
        import { compose, withProps } from "recompose";
        import PropTypes from "prop-types";
    
        class MapDirectionsRenderer extends Component {
          static propTypes = {
            waypoints: PropTypes.array,
            places: PropTypes.array
          };
    
          state = {
            directionsRef: '',
            directions: null,
            error: null
          };
    
          componentDidMount() {
            const { places, origDest } = this.props;
            const waypointsArray = places.map(p => ({
              location: p.geocode,
              stopover: true
            }));
            const origin = origDest.origin_geocode;
            const destination = origDest.destination_geocode;
            const directionsService = new window.google.maps.DirectionsService();
            directionsService.route(
              {
                origin: origin,
                destination: destination,
                travelMode: window.google.maps.TravelMode.DRIVING,
                waypoints: waypointsArray.length >= 1 ? waypointsArray : [],
              },
              (result, status) => {
                if (status === window.google.maps.DirectionsStatus.OK) {
                  this.setState({
                    directions: result,
                  });
                }
              }
            );
          }
          render() {
            return (
              this.state.directions && (
                <DirectionsRenderer
                  directions={this.state.directions}
                />
              )
            );
          }
        }
    
        const MapView = compose(
          withProps({
            googleMapURL: "https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY_HERE&v=3.exp",
            loadingElement: <div style={{ height: `100%` }} />,
            containerElement: <div style={{ height: `300px`, width: '100%' }} />,
            mapElement: <div style={{ height: `100%` }} />
          }),
          withScriptjs,
          withGoogleMap
        )(props => (
          <GoogleMap
            key={props.travelMode}
            defaultZoom={12}
            center={{ lat: 0, lng: 0 }}
          >
            <MapDirectionsRenderer
              places={props.wayPoints}
              origDest={props.originDestination}
            />
          </GoogleMap >
        ));
    
        export default MapView;
    

    【讨论】:

    • 欢迎来到 StackOverflow!虽然这个答案可能会有所帮助,但请添加解释,以便 StackOverflow 社区更容易理解
    猜你喜欢
    • 2013-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-16
    • 2021-01-20
    • 2020-12-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多