google maps react 在单个到多个路由之间切换

google maps react switching between single to multiple routes

大家好,我正在开发旅行应用程序,我尝试在单条路线和多条路线之间正常切换。 如果数组路线中只有 2 个点,则具有多条路线功能 - 我将在地图上看到点“A”和点“C”。 如果有超过 2 个点,地图将正确显示这些点。 如果它有帮助,这里是 repro: https://github.com/nguyaniv/Travel-Iceland

/* global google */
import { DirectionsRenderer } from '@react-google-maps/api';
import { selectRoutes } from '../store/reducers/attractionsSlice'
import { useSelector } from 'react-redux'
import React from 'react'
import { useState, useEffect } from 'react'

const MyDirectionsRenderer = (props) => {
    const [directions, setDirections] = useState(null);
    const routes = useSelector(selectRoutes)
    const { travelMode } = props;


    useEffect(() => {
        const directionsService = new google.maps.DirectionsService();
        const routesCopy = routes.map((route) => {
            return {
                location: { lat: route.location.lat, lng: route.location.lng },
                stopover: true
            }
        })
        const origin = routesCopy.length === 1 ? new google.maps.LatLng(routesCopy[0].location.lat, routesCopy[0].location.lng) : routesCopy.shift().location
        const destination = routesCopy.length === 1 ? new google.maps.LatLng(routesCopy[0].location.lat, routesCopy[0].location.lng) : routesCopy.pop().location
        const waypoints =  routesCopy


// here is the function for multiple routes:

        directionsService.route(

            {
                origin,
                destination,
                travelMode,
                waypoints
            },
            (result, status) => {
                if (status === google.maps.DirectionsStatus.OK) {
                    setDirections(result);
                } else {
                    console.error(`error fetching directions ${result}`);
                }
            }
        );
    }, [routes, travelMode]);
    return (
        <React.Fragment>
            {directions && <DirectionsRenderer directions={directions} />}
        </React.Fragment>
    );
}

export default MyDirectionsRenderer


我确实尝试使用 if else 来尝试在单条路线和多条路线之间进行切换:


routesCopy.length === 2 ?

 directionsService.route(

            {
                origin,
                destination,
                travelMode,
                
            },
result, status) => {
                if (status === google.maps.DirectionsStatus.OK) {
                    setDirections(result);
                } else {
                    console.error(`error fetching directions ${result}`);
                }
            }
              : 
        
directionsService.route(

            {
                origin,
                destination,
                travelMode,
                waypoints
            },
           


但现在只有一条路线有效,地图上显示的是 A 点和 B 点, 但是当添加另一个点(数组中的 3 条路线)时,地图将点 A 和点 B 显示为 C,并且当将另一条路线添加到数组(4 条路线)时,它得到修复。

在您的用例中,如果您通过单条路线(2 个坐标)和多条路线(3 个或更多坐标),您希望代码自动处理路线路线。如果数组传递 2 个坐标,则地图应显示路线起点和终点的 A 点和 C 点,而如果数组有 3 个或更多坐标,则地图应显示 A, B, C 。 . .

下面是一个 sample code(添加您的 API 键即可工作)和下面的代码片段,显示了此用例。请参阅内联评论以获取更多信息。注意:我使用 json 文件来传递坐标数组。

Map.js

/*global google*/
import ReactDOM from "react-dom";
import React from "react";

import { GoogleMap, DirectionsRenderer } from "@react-google-maps/api";

//use routes3.json for multiple coordinates inarray
//use routes2.json for only 2 coordinates in array
import routes from "./routes3.json";

//console.log(routes)

const defaultLocation = { lat: 40.756795, lng: -74.954298 };
let directionsService;
class Map extends React.Component {
  state = {
    directions: null,
    bounds: null
  };

  onMapLoad = map => {
    directionsService = new google.maps.DirectionsService();

    const routesCopy = routes.map(route => {
      return {
        location: { lat: route.location.lat, lng: route.location.lng },
        stopover: true
      };
    });

    const origin =
      routesCopy.length === 1
        ? new google.maps.LatLng(
            routesCopy[0].location.lat,
            routesCopy[0].location.lng
          )
        : routesCopy.shift().location;
    const destination =
      routesCopy.length === 1
        ? new google.maps.LatLng(
            routesCopy[0].location.lat,
            routesCopy[0].location.lng
          )
        : routesCopy.pop().location;
    //put all the remaining coordinates in waypoints after(pop and shift)
    const waypoints = routesCopy;

    console.log(origin, destination, waypoints);
    //call getDirection function
    this.getDirection(origin, destination, waypoints);
  };

  //function that is calling the directions service
  getDirection = (origin, destination, waypoints) => {
    //this will check if there is a waypoint meaning the array  has 3 or more coordinates
    waypoints.length >= 1
      ? directionsService.route(
          {
            origin: origin,
            destination: destination,
            travelMode: google.maps.TravelMode.DRIVING,
            waypoints: waypoints
          },
          (result, status) => {
            if (status === google.maps.DirectionsStatus.OK) {
              //changing the state of directions to the result of direction service
              this.setState({
                directions: result
              });
            } else {
              console.error(`error fetching directions ${result}`);
            }
          }
        )
      : directionsService.route(
          {
            origin: origin,
            destination: destination,
            travelMode: google.maps.TravelMode.DRIVING
          },
          (result, status) => {
            if (status === google.maps.DirectionsStatus.OK) {
              //changing the state of directions to the result of direction service
              this.setState({
                directions: result
              });
            } else {
              console.error(`error fetching directions ${result}`);
            }
          }
        );
  };

  render() {
    return (
      <div>
        <GoogleMap
          center={defaultLocation}
          zoom={3}
          onLoad={map => this.onMapLoad(map)}
          mapContainerStyle={{ height: "400px", width: "800px" }}
        >
          {this.state.directions !== null && (
            <DirectionsRenderer directions={this.state.directions} />
          )}
        </GoogleMap>
      </div>
    );
  }
}

export default Map;

routes2.json

[{"location": {
  "id": "ID of FIrst Place",
  "lat":40.756795,
  "lng":-73.954298
}},
{"location": {
  "id": "ID of Second Place",
  "lat":40.753167,
  "lng":-73.968120
}}]

routes3.json

[{"location": {
  "id": "ID of FIrst Place",
  "lat":40.756795,
  "lng":-73.954298
}},
{"location": {
  "id": "ID of Second Place",
  "lat":40.753167,
  "lng":-73.968120
}},
{"location": {
  "id": "ID of Third Place",
  "lat":40.853167,
  "lng":-73.968120
}}]