【问题标题】:React-google-maps render directionsReact-google-maps 渲染方向
【发布时间】:2017-06-12 15:50:08
【问题描述】:

我正在使用 react-google-maps 包 https://github.com/tomchentw/react-google-maps 向 google maps javascript API 方向服务 https://developers.google.com/maps/documentation/javascript/examples/directions-simple 发出请求。我按预期从 API 获取响应并将其记录到浏览器,但我无法弄清楚如何让折线在地图组件中呈现。

这行代码 directionsDisplay.setMap(map); 正在返回

的错误

“InvalidValueError:setMap:不是地图方向的实例”。

所以我将其注释掉,因为似乎地图是通过将handleMapLoad() 通过 refs 传递给 GoogleMap 组件来设置的。非常感谢有关如何显示折线的一些指导。

    /*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>
         );
       }
     }

【问题讨论】:

    标签: javascript google-maps reactjs


    【解决方案1】:

    您可以使用 react-google-maps Polyline 组件来渲染方向。它为我们提供了额外的造型道具options。这是一种比使用DirectionRender 组件更好的方法。以下是在您的 Google 地图上将路线显示为 Polyline 时必须遵循的步骤:

    • 使用谷歌地图方向服务并像这样从中提取overview_pathoverview_path 是一个包含 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}`);
          }
        });
    
    • 然后将这些坐标作为&lt;Polyline /&gt; 组件的path 属性传递;

    ...

    <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。首先从react-google-maps导入Polyline

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

    【讨论】:

      【解决方案2】:

      在 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;
      

      在你的 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;
      

      【讨论】:

      • 我也在使用这个 react-google-maps 包。我想在 DirectionsRenderer 中自定义标记而不是指针 A 和 B,任何人解释一下
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-16
      • 2020-09-05
      • 2022-08-22
      • 1970-01-01
      • 2021-05-28
      • 1970-01-01
      相关资源
      最近更新 更多