首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用google-map-react绘制路线?

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

Stack Overflow用户
提问于 2018-12-17 04:49:47
回答 1查看 953关注 0票数 2

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

这就是我的东西

this.map =(缩放,纬度,lng) => {让DirectionsService =新的window.google.maps.DirectionsService();

代码语言:javascript
复制
  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}`);
      }
    }
  );
EN

回答 1

Stack Overflow用户

发布于 2020-12-29 10:56:16

您可以这样做(sample code和下面的代码片段),在加载API时传递地图对象,然后使用apiIsLoaded函数调用directions服务。

代码语言:javascript
复制
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;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53806359

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档