简体   繁体   English

React-google-maps 渲染方向

[英]React-google-maps render directions

I am working with the react-google-maps package https://github.com/tomchentw/react-google-maps to make a request to the google maps javascript API directions service https://developers.google.com/maps/documentation/javascript/examples/directions-simple .我正在使用 react-google-maps 包https://github.com/tomchentw/react-google-maps向谷歌地图 javascript API 方向服务https://developers.google.com/maps/发出请求文档/javascript/examples/directions-simple I am getting the response back from the API as expected and can log it to the browser but I can not figure out how to get the polyline to render in the map component.我按预期从 API 得到响应,并且可以将其记录到浏览器,但我不知道如何让折线在地图组件中呈现。

This line of code directionsDisplay.setMap(map);这行代码directionsDisplay.setMap(map); was returning an error of返回错误

"InvalidValueError: setMap: not an instance of Map directions". “InvalidValueError:setMap:不是地图方向的实例”。

So I commented it out because it seems that the map is set by passing the handleMapLoad() to the GoogleMap component through refs.所以我把它注释掉了,因为似乎地图是通过 refs 将handleMapLoad()传递给 GoogleMap 组件来设置的。 Some guidance on how to display the polyline would be much appreciated.非常感谢有关如何显示折线的一些指导。

    /*global google*/
    import React, { Component } from "react";
    import { withGoogleMap, GoogleMap } from "react-google-maps";

    const GettingStartedGoogleMap = withGoogleMap(props => (
      <GoogleMap
        ref={props.onMapLoad}
        defaultZoom={5}
        defaultCenter={{lat: 41.85, lng: -117.65}}
      >
      </GoogleMap>
    ));

    export default class GettingStartedExample extends Component {
      handleMapLoad = this.handleMapLoad.bind(this);

      handleMapLoad(map) {
        this.mapComponent = map;
        if (map) {
          console.log(map.getZoom());
        }
        const directionsService = new google.maps.DirectionsService();
        const directionsDisplay = new google.maps.DirectionsRenderer(); 

        // directionsDisplay.setMap(map);

        const makeRequest = function() {
          calculateAndDisplayRoute(directionsService, directionsDisplay);
        };
        function calculateAndDisplayRoute(directionsService, directionsDisplay) {
           directionsService.route({
             origin: 'San Francisco',
             destination: 'Portland',
             travelMode: 'DRIVING'
          }, function(response, status) {
            if (status === 'OK') {
              directionsDisplay.setDirections(response);
              console.log(response)
            } else {
              window.alert('Directions request failed due to ' + status);
            }
          });
        }
        makeRequest();
      }
      render() {
        return (
          <div style={{height: `500px`}}>
            <GettingStartedGoogleMap
              containerElement={<div style={{ height: `100%` }} />}
              mapElement={<div style={{ height: `100%` }} />}
              onMapLoad={this.handleMapLoad}
            />
          </div>
         );
       }
     }

You can use react-google-maps Polyline component to render direction.您可以使用 react-google-maps Polyline组件来渲染方向。 It gives us additional styling prop options .它为我们提供了额外的造型道具options It is a way better approach than using the DirectionRender component.这是一种比使用DirectionRender组件更好的方法。 Here are the steps you must follow to render directions as Polyline on your Google Map:以下是在 Google 地图上将路线渲染为Polyline时必须遵循的步骤:

  • Use google maps direction service and extract overview_path from it like this;使用谷歌地图方向服务并像这样从中提取overview_path overview_path is an array of objects containing Lat and Lng . overview_path _ Lng是一个包含LatLng的对象数组。

... ...

DirectionsService.route({   
   origin: 'San Francisco', 
   destination: 'Portland',   
   travelMode: google.maps.TravelMode.DRIVING,   
  },  
    (result, status) => {   
      if (status === google.maps.DirectionsStatus.OK) {   
        const overViewCoords = result.routes[0].overview_path;   
          this.setState({   
            lineCoordinates: overViewCoords,
          });
      } else {
         console.warn(`error fetching directions ${status}`);
      }
    });
  • Then pass these coordinates as the path prop of the <Polyline /> Component;然后将这些坐标作为<Polyline />组件的path prop 传递;

... ...

<GoogleMap
    ref={props.onMapLoad}
    defaultZoom={5}
    defaultCenter={{lat: 41.85, lng: -117.65}}
  >
  <Polyline
        path={this.state.lineCoordinates}
        geodesic={false}
        options={{
            strokeColor: '#38B44F',
            strokeOpacity: 1,
            strokeWeight: 7,
        }}
    />
</GoogleMap>

PS.附注。 import Polyline from react-google-maps first:首先从react-google-maps导入Polyline

import { Polyline } from 'react-google-maps';

A very simple and direct way to render directions in React using waypoints too在 React 中也使用航点渲染方向的一种非常简单直接的方法

import React from 'react';
import logo from './logo.svg';
import './App.css';
import { withScriptjs } from "react-google-maps";




import  Map from './components/Map';

function App() {

  const MapLoader = withScriptjs(Map);

  return (

<div className="App">
  <header className="App-header">
    <img src={logo} className="App-logo" alt="logo" />

  </header>
  <MapLoader
      googleMapURL="https://maps.googleapis.com/maps/api/js?key=Key"
      loadingElement={<div style={{ height: `100%` }} />}
  />
</div>
  );
}

export default App;

And in your Map.js file在你的 Map.js 文件中

/*global google*/
import React, { Component } from "react";
import {
    withGoogleMap,
    withScriptjs,
    GoogleMap,
    DirectionsRenderer
} from "react-google-maps";
class Map extends Component {
    state = {
        directions: null,


};

componentDidMount() {
    const directionsService = new google.maps.DirectionsService();

    const origin = { lat: 6.5244, lng:  3.3792 };
    const destination = { lat: 6.4667, lng:  3.4500};

    directionsService.route(
        {
            origin: origin,
            destination: destination,
            travelMode: google.maps.TravelMode.DRIVING,
            waypoints: [
                {
                    location: new google.maps.LatLng(6.4698,  3.5852)
                },
                {
                    location: new google.maps.LatLng(6.6018,3.3515)
                }
            ]
        },
        (result, status) => {
            if (status === google.maps.DirectionsStatus.OK) {
                console.log(result)
                this.setState({
                    directions: result
                });
            } else {
                console.error(`error fetching directions ${result}`);
            }
        }
    );
}

render() {
    const GoogleMapExample = withGoogleMap(props => (
        <GoogleMap
            defaultCenter={{ lat: 6.5244, lng:  3.3792 }}
            defaultZoom={13}
        >
            <DirectionsRenderer
                directions={this.state.directions}
            />
        </GoogleMap>
    ));

    return (
        <div>
            <GoogleMapExample
                containerElement={<div style={{ height: `500px`, width: "500px" }} />}
                mapElement={<div style={{ height: `100%` }} />}
            />
        </div>


       );
    }
}

export default Map;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM