首页 > 解决方案 > 如何在我的项目中实现 react-google-maps DirectionsRenderer

问题描述

我正在构建一个简单的项目,如果用户单击一个按钮,它应该显示从用户位置到我标记的目的地的方向。这是我的代码。我刚刚实现了一些部分,但我不明白如何实现 DirectionsRenderer,也无法从文章、文档中学习。现在我不知道该怎么办。谁能用更简单的方式解释我?谢谢!

  GoogleMap,
  withGoogleMap,
  withScriptjs,
  DirectionsRenderer,
} from 'react-google-maps';

import Marker from 'react-google-maps/lib/components/Marker';
function Map() {
  return (
    <div className='App'>
      <GoogleMap
        defaultZoom={10}
        defaultCenter={{ lat: 51.507351, lng: -0.127758 }}
      >
        <Marker position={{ lat: 51.4666, lng: -0.213 }} />
      </GoogleMap>
    </div>
  );
}
const DirectionsService = new window.google.maps.DirectionsService();
DirectionsService.route({
  origin: new window.google.maps.LatLng(41.85073, -87.65126),
  destination: new window.google.maps.LatLng(41.85258, -87.65141),
  travelMode: window.google.maps.TravelMode.DRIVING,
});
const WrappedMap = withScriptjs(withGoogleMap(Map));

function App() {
  return (
    <div style={{ width: '100vw', height: '100vh' }}>
      <WrappedMap
        googleMapURL={`https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places&key=${process.env.REACT_APP_MAP_KEY}`}
        loadingElement={<div style={{ height: `100%` }} />}
        containerElement={<div style={{ height: `100%` }} />}
        mapElement={<div style={{ height: `100%` }} />}
      />
    </div>
  );
}

export default App;

标签: reactjsgoogle-maps-api-3react-google-maps

解决方案


以下是我为实现您的用例而采取的步骤:

  1. 使用浏览器HTML5 Geolocation feature获取用户在componentDidMount.
  2. 然后使用状态变量来保存当前位置的值。您还将用户当前位置状态的值放入对象的center参数中,GoogleMap以便地图将显示用户所在的地图区域。这将用作origion您的路线服务。3.还使用另一个状态来保存用户当前位置。这将用作在用户当前位置放置标记的状态。
  3. onClick在对象的参数中调用一个函数GoogleMap。然后使用另一个状态变量来保存单击坐标的值。这将用作destination方向服务的。
  4. 在您的地图 div 顶部放置一个按钮并在其OnClick参数中调用一个函数。该函数将调用GoogleMaps directionsService并计算您的起点和终点之间的路线。如果有路线,您可以使用另一个状态变量来保存路线服务的结果。
  5. 使用DirectionsRendererGoogleMap 对象内的对象来显示路线的折线。

这是示例代码注意:确保将您的 API 密钥放在 index.js 中以使示例正常工作)和下面的代码片段:

/*global google*/
import React, { Component } from 'react';
import Button from 'react-bootstrap/Button';
import {
  withGoogleMap,
  Marker,
  GoogleMap,
  DirectionsRenderer
} from 'react-google-maps';
class Map extends Component {
  state = {
    directions: null,
    markerPos: null,
    centerMarker: null,
    currentLocation: null
  };

  componentDidMount = () => {
    navigator?.geolocation.getCurrentPosition(
      ({ coords: { latitude: lat, longitude: lng } }) => {
        const pos = { lat, lng };
        this.setState({ currentLocation: pos, centerMarker: pos });
      }
    );
  };

  onMapClick = e => {
    this.setState({ markerPos: e.latLng });
  };

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

    const origin = this.state.currentLocation;
    const destination = this.state.markerPos;

    if (origin !== null && destination !== null) {
      directionsService.route(
        {
          origin: origin,
          destination: destination,
          travelMode: google.maps.TravelMode.DRIVING
        },
        (result, status) => {
          if (status === google.maps.DirectionsStatus.OK) {
            this.setState({
              directions: result
            });
          } else {
            console.error(`error fetching directions ${result}`);
          }
        }
      );
    } else {
      console.log('Please mark your destination in the map first!');
    }
  };

  render() {
    const GoogleMapExample = withGoogleMap(props => (
      <GoogleMap
        defaultCenter={{ lat: 40.756795, lng: -73.954298 }}
        defaultZoom={13}
        center={this.state.currentLocation}
        onClick={this.onMapClick}
      >
        {this.state.centerMarker !== null && (
          <Marker position={this.state.centerMarker} label={'userloc'} />
        )}
        {this.state.markerPos !== null && (
          <Marker position={this.state.markerPos} />
        )}
        {this.state.directions !== null && (
          <DirectionsRenderer
            directions={this.state.directions}
            defaultOptions={{
              suppressMarkers: true
            }}
          />
        )}
      </GoogleMap>
    ));

    return (
      <div>
        <Button onClick={this.getDirections}>Get Direction</Button>
        <GoogleMapExample
          containerElement={<div style={{ height: `500px`, width: '500px' }} />}
          mapElement={<div style={{ height: `100%` }} />}
        />
      </div>
    );
  }
}

export default Map;

推荐阅读