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

如何使用react-google-maps组件绘制路线?
EN

Stack Overflow用户
提问于 2019-03-30 04:03:41
回答 2查看 12.8K关注 0票数 5

我试图用react-google-maps在两个点之间画一条路线,但对我不起作用。你能帮我解决这个问题吗?下面是我的react组件的一个示例。

代码语言:javascript
运行
复制
import React from 'react';
import {
  withScriptjs,
  withGoogleMap,
  GoogleMap,
  Marker,
} from 'react-google-maps';
import MapDirectionsRenderer from './app_map_directions_render';

const Map = withScriptjs(
  withGoogleMap(props => (
    <GoogleMap
      defaultCenter={props.defaultCenter}
      defaultZoom={props.defaultZoom}
    >
      {props.places.map((marker, index) => {
        const position = {lat: marker.latitude, lng: marker.longitude};
        return <Marker key={index} position={position}/>;
      })}
      <MapDirectionsRenderer places={props.places} travelMode={window.google.maps.TravelMode.DRIVING} />
    </GoogleMap>
  ))
);

const AppMap = props => {
  const {places} = props;

  const {
    loadingElement,
    containerElement,
    mapElement,
    defaultCenter,
    defaultZoom
  } = props;

  return (
    <Map
      googleMapURL={
        'https://maps.googleapis.com/maps/api/js?key=' +
        googleMapsApiKey +
        '&v=3.exp&libraries=geometry,drawing,places'
      }
      places={places}
      loadingElement={loadingElement || <div style={{height: `100%`}}/>}
      containerElement={containerElement || <div style={{height: "80vh"}}/>}
      mapElement={mapElement || <div style={{height: `100%`}}/>}
      defaultCenter={defaultCenter || {lat: 25.798939, lng: -80.291409}}
      defaultZoom={defaultZoom || 11}
    />
  );
};

export default AppMap;

和我的MapDirectionsRenderer组件

代码语言:javascript
运行
复制
import React, {Component} from 'react';
import { DirectionsRenderer } from "react-google-maps";

export default class MapDirectionsRenderer extends Component {
  state = {
    directions: null,
    error: null
  };

  componentDidMount() {
    const { places, travelMode } = this.props;

    const waypoints = places.map(p =>({
        location: {lat: p.latitude, lng: p.longitude},
        stopover: true
    }))
    if(waypoints.length >= 2){
    const origin = waypoints.shift().location;
    const destination = waypoints.pop().location;

    const directionsService = new window.google.maps.DirectionsService();
    directionsService.route(
      {
        origin: origin,
        destination: destination,
        travelMode: travelMode,
        waypoints: waypoints
      },
      (result, status) => {
        if (status === window.google.maps.DirectionsStatus.OK) {
          this.setState({
            directions: result
          });
        } else {
          this.setState({ error: result });
        }
      }
    );
    }
  }

  render() {
    if (this.state.error) {
      return <h1>{this.state.error}</h1>;
    }
    return <DirectionsRenderer directions={this.state.directions} />;
  }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-04-01 03:29:14

为了呈现路由,Google Maps API提供了Directions Service,如果是react-google-maps library DirectionsRenderer component,它是DirectionsRenderer class的包装器,反过来:

呈现从DirectionsService获取的方向。

假设路由的数据以以下格式提供:

代码语言:javascript
运行
复制
const places = [
  {latitude: 25.8103146,longitude: -80.1751609},
  {latitude: 27.9947147,longitude: -82.5943645},
  {latitude: 28.4813018,longitude: -81.4387899},
  //...
]

可以引入以下组件来通过react-google-maps library计算和呈现方向

代码语言:javascript
运行
复制
class MapDirectionsRenderer extends React.Component {
  state = {
    directions: null,
    error: null
  };

  componentDidMount() {
    const { places, travelMode } = this.props;

    const waypoints = places.map(p =>({
        location: {lat: p.latitude, lng:p.longitude},
        stopover: true
    }))
    const origin = waypoints.shift().location;
    const destination = waypoints.pop().location;



    const directionsService = new google.maps.DirectionsService();
    directionsService.route(
      {
        origin: origin,
        destination: destination,
        travelMode: travelMode,
        waypoints: waypoints
      },
      (result, status) => {
        if (status === google.maps.DirectionsStatus.OK) {
          this.setState({
            directions: result
          });
        } else {
          this.setState({ error: result });
        }
      }
    );
  }

  render() {
    if (this.state.error) {
      return <h1>{this.state.error}</h1>;
    }
    return <DirectionsRenderer directions={this.state.directions} />;
  }
}

Here is a demo

对于React 16.8或更高版本,可以(使用Hooks)实现MapDirectionsRenderer,如下所示:

代码语言:javascript
运行
复制
function MapDirectionsRenderer(props) {
  const [directions, setDirections] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    const { places, travelMode } = props;

    const waypoints = places.map(p => ({
      location: { lat: p.latitude, lng: p.longitude },
      stopover: true
    }));
    const origin = waypoints.shift().location;
    const destination = waypoints.pop().location;

    const directionsService = new google.maps.DirectionsService();
    directionsService.route(
      {
        origin: origin,
        destination: destination,
        travelMode: travelMode,
        waypoints: waypoints
      },
      (result, status) => {
        console.log(result)
        if (status === google.maps.DirectionsStatus.OK) {
          setDirections(result);
        } else {
          setError(result);
        }
      }
    );
  });

  if (error) {
    return <h1>{error}</h1>;
  }
  return (
    directions && (
      <DirectionsRenderer directions={directions} />
    )
  );
}
票数 8
EN

Stack Overflow用户

发布于 2021-11-08 20:54:54

要使用DataLayer,您需要有访问映射对象的权限。库在onGoogleApiLoaded回调中提供了这一点。在该回调中,将对map对象的引用存储在模块级变量或宿主组件状态中。我选择了模块级,它工作得很好。然后,您可以在您的组件中使用一个自定义的drawMyGeoJson方法,并对地图对象做任何您喜欢做的事情,该对象公开了完整的Google Maps API。在组件的render()中调用此自定义方法。

你可以看到这个线程https://github.com/google-map-react/google-map-react/issues/149

或者文档中直接的https://developers.google.com/maps/documentation/javascript/datalayer

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55424790

复制
相关文章

相似问题

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