Как отобразить маршрут на ReactGoogleMap? - PullRequest
0 голосов
/ 06 мая 2020

Опишите ошибку ?

Используя Google Maps API, я получаю указания и создаю DirectionsRenderer. Все выглядит правильно, карта отображается, но маршрут не отображается, не уверен, что эта опция недоступна в GoogleMapReact

Воспроизвести ?

Шаги для воспроизведения поведения:

  1. Добавьте запрос на получение направлений в конструкторе
constructor(props: any){
    super(props)
    const DirectionsService = new google.maps.DirectionsService();
    this.state = {};

    DirectionsService.route(
      {
        origin: new google.maps.LatLng(19.5682414, -99.0436029),
        destination: new google.maps.LatLng(19.7682414, -99.0436029),
        travelMode: window.google.maps.TravelMode.DRIVING,
      },
      (result, status) => {
        // console.log("status", status);
        if (status === window.google.maps.DirectionsStatus.OK) {
          this.setState({
            directions: result,
          });
          console.log(result);
        } else {
          console.error(`error fetching directions ${result}`);
        }
      }
    );

image

На этом этапе направления установлены в состоянии, поэтому давайте попробуем чтобы отобразить его.

render() {
    return (
      // Important! Always set the container height explicitly
      <div id="BrainMap" className="schedulerMap  justify-content-md-left">
        <GoogleMapReact
          bootstrapURLKeys={{ key: process.env.REACT_APP_MAPS_API_KEY }}
          defaultCenter={this.initialPosition.center}
          defaultZoom={this.initialPosition.zoom}
        >

          {this.state.directions && (
            <DirectionsRenderer
              directions={this.state.directions}
              options={{
                polylineOptions: {
                  strokeOpacity: 0.4,
                  strokeWeight: 4,
                },
                preserveViewport: true,
                suppressMarkers: true,
              }}
            />
          )}
        </GoogleMapReact>
      </div>
    );
  }

Ожидаемое поведение ?

Я ожидаю увидеть маршрут, отображаемый на карте.

Другой контекст

В других примерах похоже, что они используют другой компонент GoogleMap и другие функции с составлением, я бы хотел избежать этого.

Код

import React, { Component } from "react";

import GoogleMapReact from "google-map-react";
import { DirectionsRenderer  } from "react-google-maps";

import MapCard from "../commons/MapCard";

import "./Scheduler.css";

type BrainMapState = {
  directions?: any;
}

class BrainMap extends Component {
  state: BrainMapState;
  initialPosition = {
    center: {
      lat: 19.4978,
      lng: -99.1269,
    },
    zoom: 12,
  };

  constructor(props: any){
    super(props)
    const DirectionsService = new google.maps.DirectionsService();
    this.state = {};

    DirectionsService.route(
      {
        origin: new google.maps.LatLng(19.5682414, -99.0436029),
        destination: new google.maps.LatLng(19.7682414, -99.0436029),
        travelMode: window.google.maps.TravelMode.DRIVING,
      },
      (result, status) => {
        // console.log("status", status);
        if (status === window.google.maps.DirectionsStatus.OK) {
          this.setState({
            directions: result,
          });
          console.log(result);
        } else {
          console.error(`error fetching directions ${result}`);
        }
      }
    );

    //const directionsRenderer = new google.maps.DirectionsRenderer();
}

  render() {
    return (
      // Important! Always set the container height explicitly
      <div id="BrainMap" className="schedulerMap  justify-content-md-left">
        <GoogleMapReact
          bootstrapURLKeys={{ key: process.env.REACT_APP_MAPS_API_KEY }}
          defaultCenter={this.initialPosition.center}
          defaultZoom={this.initialPosition.zoom}
        >
          {this.state.directions && (
            <DirectionsRenderer
              directions={this.state.directions}
              options={{
                polylineOptions: {
                  strokeOpacity: 0.4,
                  strokeWeight: 4,
                },
                preserveViewport: true,
                suppressMarkers: true,
              }}
            />
          )}
        </GoogleMapReact>
      </div>
    );
  }
}

export default BrainMap;

1 Ответ

1 голос
/ 14 мая 2020

Поскольку GoogleMapReact библиотека не поддерживает API службы маршрутов , для отрисовки направлений можно использовать следующий компонент:

 function DirectionsRenderer(props: {
  map: google.maps.Map | null;
  origin: google.maps.LatLngLiteral;
  destination: google.maps.LatLngLiteral;
}) {
  async function getRoute(
    origin: google.maps.LatLngLiteral,
    destination: google.maps.LatLngLiteral
  ): Promise<google.maps.DirectionsResult> {
    const directionsService = new google.maps.DirectionsService();
    return new Promise(function (resolve, reject) {
      directionsService.route(
        {
          origin: origin,
          destination: destination,
          travelMode: google.maps.TravelMode.DRIVING,
        },
        (result: any, status: google.maps.DirectionsStatus) => {
          if (status === google.maps.DirectionsStatus.OK) {
            resolve(result);
          } else {
            reject(result);
          }
        }
      );
    });
  }

  async function renderRoute() {
    const directions = await getRoute(props.origin, props.destination);
    const directionsRenderer = new google.maps.DirectionsRenderer();
    directionsRenderer.setMap(props.map);
    directionsRenderer.setDirections(directions);
  }

  useEffect(() => {
    renderRoute().catch((err) => {
      console.log(err);
    });
  }, []);

  return null;
}

Использование

function MapWithADirectionsRenderer(props: {
  center: google.maps.LatLngLiteral;
  zoom: number;
}) {
  const [map, setMap] = useState<google.maps.Map | null>(null);

  function handleApiLoaded(mapInstance: google.maps.Map, google: any) {
    setMap(mapInstance);
  }

  return (
    <div style={{ height: "100vh", width: "100%" }}>
      <GoogleMapReact
        bootstrapURLKeys={{ key: "--Google Maps Key goes here--" }}
        defaultCenter={props.center}
        defaultZoom={props.zoom}
        onGoogleApiLoaded={({ map, maps }) => handleApiLoaded(map, maps)}
      >
        {map && (
          <DirectionsRenderer
            map={map}
            origin={{ lat: 40.756795, lng: -73.954298 }}
            destination={{ lat: 41.756795, lng: -78.954298 }}
          />
        )}
      </GoogleMapReact>
    </div>
  );
}

Демо

Примечание. Необходимо указать ключ Google Maps

Результат

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...