Проблема, связанная с передачей обратного вызова из API GMaps компоненту DirectionsRenderer изact-google-maps - PullRequest
0 голосов
/ 18 сентября 2018

Я пытаюсь отобразить карты с маршрутом направления между 2 точками.Итак, я построил:

Класс контейнера:

import React, { Component } from 'react';
import { DirectionsRenderer } from 'react-google-maps';
import Map from './Map';

class MapContainer extends Component {
  constructor(props) {
    super(props);
    this.state = { directions: null };
  }
  componentWillMount() {
    const DirectionsService = new google.maps.DirectionsService();
    DirectionsService.route(
      {
        origin: new google.maps.LatLng(41.85073, -87.65126),
        destination: new google.maps.LatLng(41.85258, -87.65141),
        travelMode: google.maps.TravelMode.DRIVING
      },
      (result, status) => {
        if (status === google.maps.DirectionsStatus.OK) {
          this.setState({
            directions: result
          });
        } else {
          console.error(`error fetching directions ${result}`);
        }
      }
    );
  }
  render() {
    return (
      <Map
        googleMapURL={`https://maps.googleapis.com/maps/api/js?key=<APIKEY>&v=3.exp&libraries=geometry,drawing,places`}
        loadingElement={<div style={{ height: `100%` }} />}
        containerElement={<div style={{ height: `600px`, width: `100%` }} />}
        mapElement={<div style={{ height: `100%` }} />}
        directions={this.state.directions}
      />
    );
  }
}

export default MapContainer;

Он обнаруживает жизненный цикл REACT и получает код JS из API GMaps, а затем передает его компоненту Map:

import React, { Component } from 'react';
import {
  withScriptjs,
  withGoogleMap,
  GoogleMap,
  Marker,
  DirectionsRenderer
} from 'react-google-maps';
import package_ico from '../img/package.png';

const Map = withScriptjs(
  withGoogleMap(props => {
    const marker_package = (
      <Marker
        position={{
          lat: 41.85073,
          lng: -87.65126
        }}
        icon={package_ico}
      />
    );
    const marker_destination = (
      <Marker
        position={{
          lat: 41.85258,
          lng: -87.65141
        }}
      />
    );
    if (props.directions != null) {
      console.log('renderdir');
      console.log(props.directions);

      return (
        <GoogleMap defaultZoom={14} center={{ lat: 41.85073, lng: -87.65126 }}>
          {marker_package}
          {marker_destination}
          {props.directions && (
            <DirectionsRenderer directions={props.directions} />
          )}
        </GoogleMap>
      );
    } else {
      console.log('rendernodirec');
      return (
        <GoogleMap defaultZoom={14} center={{ lat: 41.85073, lng: -87.65126 }}>
          {marker_package}
          {marker_destination}
        </GoogleMap>
      );
    }
  })
);

export default Map;

Данные правильно передаются из MapContainer на карту, но затем кажется, что компонент DirectionsRenderer, который должен управлять результатом, не получает данные правильно, и я получаю следующее сообщение об ошибке.

57 Uncaught Fc {message: "not a LatLngBounds or LatLngBoundsLiteral: unknown property f", name: "InvalidValueError", stack: "Error↵    at new Fc (https://maps.googleapis.com/m…3.exp&libraries=geometry,drawing,places:170:4324)"}
message: "not a LatLngBounds or LatLngBoundsLiteral: unknown property f"
name: "InvalidValueError"

Что я делаю не так?Я попытался последовать примеру: https://tomchentw.github.io/react-google-maps/#directionsrenderer, но я бы хотел избежать использования перекомпоновки, поскольку мне это показалось довольно запутанным ...

Спасибо за ваш отзыв.

1 Ответ

0 голосов
/ 19 сентября 2018

Мне не удалось воспроизвести ту же ошибку, но это могла быть последовательность загрузки скрипта Google Maps.Так как вы используете withScriptJs, ваш вызов google.maps.* должен быть внутри компонента, который заключен в withScriptJs, где в вашем примере он находится снаружи.Попробуйте переместить функцию componentWillMount в компонент Map, как показано в примере ниже.

Если это решит проблему, это будет состояние гонки, вызванное тем, что скрипт Google Maps не загружается до того, как componentWillMount будетсрабатывает и google.maps.* будет недоступно.

У меня есть рабочий пример CodeSandbox здесь .Большая часть кода скопирована из ваших примеров выше.Просто вставьте свой ключ API.

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

class Map extends React.Component {
  constructor(props) {
    super(props);
    this.state = { directions: null };
  }

  componentWillMount() {
    const DirectionsService = new google.maps.DirectionsService();
    DirectionsService.route(
      {
        origin: new google.maps.LatLng(41.85073, -87.65126),
        destination: new google.maps.LatLng(41.85258, -87.65141),
        travelMode: google.maps.TravelMode.DRIVING
      },
      (result, status) => {
        if (status === google.maps.DirectionsStatus.OK) {
          this.setState({
            directions: result
          });
        } else {
      console.error(`error fetching directions ${result}`);
        }
      }
    );
  }

  render() {
    const marker_package = (
      <Marker
        position={{
          lat: 41.85073,
          lng: -87.65126
        }}
      />
    );
    const marker_destination = (
      <Marker
        position={{
          lat: 41.85258,
          lng: -87.65141
        }}
      />
    );
    if (this.state.directions != null) {
      console.log("renderdir");
      console.log(this.state.directions);

      return (
        <GoogleMap defaultZoom={14} center={{ lat: 41.85073, lng: -87.65126 }}>
          {marker_package}
          {marker_destination}
          {this.state.directions && (
            <DirectionsRenderer directions={this.state.directions} />
          )}
        </GoogleMap>
      );
    } else {
      console.log("rendernodirec");
      return (
        <GoogleMap defaultZoom={14} center={{ lat: 41.85073, lng: -87.65126 }}>
          {marker_package}
          {marker_destination}
        </GoogleMap>
      );
    }
  }
}

export default withScriptjs(withGoogleMap(Map));
...