【问题标题】:How i draw a route with react-google-maps component?我如何使用 react-google-maps 组件绘制路线?
【发布时间】:2019-08-20 19:53:57
【问题描述】:

我正在使用 react-google-maps 在两点之间绘制一条路线,但对我不起作用。你能帮我解决这个问题吗?这是我的反应组件的示例。

import React from 'react';
import {
  withScriptjs,
  withGoogleMap,
  GoogleMap,
  Marker,
} from 'react-google-maps';
import MapDirectionsRenderer from './app_map_directions_render';

const Map = withScriptjs(
  withGoogleMap(props => (
    <GoogleMap
      defaultCenter={props.defaultCenter}
      defaultZoom={props.defaultZoom}
    >
      {props.places.map((marker, index) => {
        const position = {lat: marker.latitude, lng: marker.longitude};
        return <Marker key={index} position={position}/>;
      })}
      <MapDirectionsRenderer places={props.places} travelMode={window.google.maps.TravelMode.DRIVING} />
    </GoogleMap>
  ))
);

const AppMap = props => {
  const {places} = props;

  const {
    loadingElement,
    containerElement,
    mapElement,
    defaultCenter,
    defaultZoom
  } = props;

  return (
    <Map
      googleMapURL={
        'https://maps.googleapis.com/maps/api/js?key=' +
        googleMapsApiKey +
        '&v=3.exp&libraries=geometry,drawing,places'
      }
      places={places}
      loadingElement={loadingElement || <div style={{height: `100%`}}/>}
      containerElement={containerElement || <div style={{height: "80vh"}}/>}
      mapElement={mapElement || <div style={{height: `100%`}}/>}
      defaultCenter={defaultCenter || {lat: 25.798939, lng: -80.291409}}
      defaultZoom={defaultZoom || 11}
    />
  );
};

export default AppMap;

还有我的MapDirectionsRenderer 组件

import React, {Component} from 'react';
import { DirectionsRenderer } from "react-google-maps";

export default class MapDirectionsRenderer extends Component {
  state = {
    directions: null,
    error: null
  };

  componentDidMount() {
    const { places, travelMode } = this.props;

    const waypoints = places.map(p =>({
        location: {lat: p.latitude, lng: p.longitude},
        stopover: true
    }))
    if(waypoints.length >= 2){
    const origin = waypoints.shift().location;
    const destination = waypoints.pop().location;

    const directionsService = new window.google.maps.DirectionsService();
    directionsService.route(
      {
        origin: origin,
        destination: destination,
        travelMode: travelMode,
        waypoints: waypoints
      },
      (result, status) => {
        if (status === window.google.maps.DirectionsStatus.OK) {
          this.setState({
            directions: result
          });
        } else {
          this.setState({ error: result });
        }
      }
    );
    }
  }

  render() {
    if (this.state.error) {
      return <h1>{this.state.error}</h1>;
    }
    return <DirectionsRenderer directions={this.state.directions} />;
  }
}

【问题讨论】:

    标签: javascript reactjs routes react-google-maps


    【解决方案1】:

    要渲染路线,Google Maps API 提供了Directions Service,如果react-google-maps library 可用,DirectionsRenderer componentDirectionsRenderer class 的包装器,而DirectionsRenderer class 反过来:

    渲染从DirectionsService获得的方向。

    假设路线的数据以下列格式提供:

    const places = [
      {latitude: 25.8103146,longitude: -80.1751609},
      {latitude: 27.9947147,longitude: -82.5943645},
      {latitude: 28.4813018,longitude: -81.4387899},
      //...
    ]
    

    可以通过react-google-maps library引入以下组件来计算和渲染方向

    class MapDirectionsRenderer extends React.Component {
      state = {
        directions: null,
        error: null
      };
    
      componentDidMount() {
        const { places, travelMode } = this.props;
    
        const waypoints = places.map(p =>({
            location: {lat: p.latitude, lng:p.longitude},
            stopover: true
        }))
        const origin = waypoints.shift().location;
        const destination = waypoints.pop().location;
    
    
    
        const directionsService = new google.maps.DirectionsService();
        directionsService.route(
          {
            origin: origin,
            destination: destination,
            travelMode: travelMode,
            waypoints: waypoints
          },
          (result, status) => {
            if (status === google.maps.DirectionsStatus.OK) {
              this.setState({
                directions: result
              });
            } else {
              this.setState({ error: result });
            }
          }
        );
      }
    
      render() {
        if (this.state.error) {
          return <h1>{this.state.error}</h1>;
        }
        return <DirectionsRenderer directions={this.state.directions} />;
      }
    }
    

    Here is a demo


    对于 React 16.8 或更高版本,MapDirectionsRenderer 可以实现(使用Hooks)如下:

    function MapDirectionsRenderer(props) {
      const [directions, setDirections] = useState(null);
      const [error, setError] = useState(null);
    
      useEffect(() => {
        const { places, travelMode } = props;
    
        const waypoints = places.map(p => ({
          location: { lat: p.latitude, lng: p.longitude },
          stopover: true
        }));
        const origin = waypoints.shift().location;
        const destination = waypoints.pop().location;
    
        const directionsService = new google.maps.DirectionsService();
        directionsService.route(
          {
            origin: origin,
            destination: destination,
            travelMode: travelMode,
            waypoints: waypoints
          },
          (result, status) => {
            console.log(result)
            if (status === google.maps.DirectionsStatus.OK) {
              setDirections(result);
            } else {
              setError(result);
            }
          }
        );
      });
    
      if (error) {
        return <h1>{error}</h1>;
      }
      return (
        directions && (
          <DirectionsRenderer directions={directions} />
        )
      );
    }
    

    【讨论】:

    • 没错,现在我收到一个错误'google' is not defined
    • 这是预期行为,因为 Google Maps API 应该可以全局访问,要解决它,请尝试将 /* global google */ 放在文件顶部(声明 MapDirectionsRenderer 组件的位置)
    • 这很奇怪,但它不起作用并且控制台中没有错误。只是警告。请更新以下组件:withGoogleMap(Component)
    【解决方案2】:

    要使用 DataLayer,您需要有权访问地图对象。这 库在 onGoogleApiLoaded 回调中为您提供。在那 回调,将映射对象的引用存储在模块级变量中 或您的托管组件状态。我选择了模块级别, 工作得很好。然后你可以有一个自定义的 drawMyGeoJson 方法 您的组件并使用地图对象做任何您喜欢的事情,这会暴露 完整的谷歌地图 API。在你的调用这个自定义方法 组件的 render()。

    你可以看到这个帖子https://github.com/google-map-react/google-map-react/issues/149

    或者文档直接https://developers.google.com/maps/documentation/javascript/datalayer

    【讨论】:

      猜你喜欢
      • 2019-05-17
      • 1970-01-01
      • 1970-01-01
      • 2014-08-09
      • 1970-01-01
      • 2012-12-05
      • 2019-07-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多