【问题标题】:REACT how can i draw a route with google-map-react?REACT 如何使用 google-map-react 绘制路线?
【发布时间】:2019-05-17 07:07:19
【问题描述】:

如何使用 npm google-map-react 绘制路线?

这就是我所拥有的

this.map = (zoom, lat, lng) => { 让 DirectionsService = new window.google.maps.DirectionsService();

  DirectionsService.route(
    {
      origin: new window.google.maps.LatLng(40.407749, -3.710138), //
      destination: new window.google.maps.LatLng(40.762341, -3.788512), //
      travelmode: window.google.maps.TravelMode.DRIVING
    },
    (result, status) => {
      if (status === window.google.maps.DirectionsStatus.OK) {
        this.setState({
          direction: result
        });
      } else {
        console.error(`error fetching directions ${result}`);
      }
    }
  );

【问题讨论】:

    标签: reactjs google-maps-api-3 google-map-react


    【解决方案1】:

    您可以这样做(sample code 和下面的代码 sn-p),其中您将在加载 API 时传递地图对象,然后使用 apiIsLoaded 函数调用路线服务。

    import React, { Component } from "react";
    import GoogleMapReact from "google-map-react";
    import "./style.css";
    
    class GoogleMaps extends Component {
      constructor(props) {
        super(props);
    
        this.state = {
          currentLocation: { lat: 40.756795, lng: -73.954298 }
        };
      }
    
      render() {
        const apiIsLoaded = (map, maps) => {
          const directionsService = new google.maps.DirectionsService();
          const directionsRenderer = new google.maps.DirectionsRenderer();
          directionsRenderer.setMap(map);
          const origin = { lat: 40.756795, lng: -73.954298 };
          const destination = { lat: 41.756795, lng: -78.954298 };
    
          directionsService.route(
            {
              origin: origin,
              destination: destination,
              travelMode: google.maps.TravelMode.DRIVING
            },
            (result, status) => {
              if (status === google.maps.DirectionsStatus.OK) {
                directionsRenderer.setDirections(result);
              } else {
                console.error(`error fetching directions ${result}`);
              }
            }
          );
        };
        return (
          <div>
            <div style={{ height: "400px", width: "100%" }}>
              <GoogleMapReact
                bootstrapURLKeys={{
                  key: "YOUR_API_KEY"
                }}
                defaultCenter={{ lat: 40.756795, lng: -73.954298 }}
                defaultZoom={10}
                center={this.state.currentLocation}
                yesIWantToUseGoogleMapApiInternals
                onGoogleApiLoaded={({ map, maps }) => apiIsLoaded(map, maps)}
              />
            </div>
          </div>
        );
      }
    }
    export default GoogleMaps;
    

    【讨论】:

      猜你喜欢
      • 2022-06-22
      • 2019-08-20
      • 1970-01-01
      • 2022-01-26
      • 1970-01-01
      • 2015-12-17
      • 1970-01-01
      • 2019-07-18
      • 1970-01-01
      相关资源
      最近更新 更多