【问题标题】:Google maps draw route from given coordinates谷歌地图从给定坐标绘制路线
【发布时间】:2019-07-23 20:52:05
【问题描述】:

我正在使用google-maps-react 模块,直到最后一段都很好。使用这个包,我可以点击地图,设置多个标记并“直观地”定义我的路线。我不认为Polygon 不会考虑实际街道和地图几何形状(愚蠢的我)。有人可以帮助我并建议如何在地图上提供正确绘制的路线,而不是连接标记 X 和标记 Y 的直线吗?到目前为止,这是我在视觉上看到的:

这是我在应用程序中形成的坐标数组,并通过以下方式绘制多边形:

我正在使用 Google maps api 和 google-maps-react 包。

【问题讨论】:

  • 为了显示实际路线,您需要对路线进行方向 API 调用。如您所见,多边形或线没有跟随街道和实际路线。它相当强大,您只需要执行以下操作。请记住,您将有一个起点、一个目的地,如果您需要在它们之间停靠,则称为航路点。总共可以有 25 个,developers.google.com/maps/documentation/directions/startdevelopers.google.com/maps/documentation/directions/…
  • @TheeBen,谢谢。但是您可以使用fetch 向目标api 发出请求吗?我形成一个请求,尝试获取它并返回一个未定义的响应,尽管我请求的 url 100% 没问题,因为如果我将它直接输入浏览器,我可以看到 json 数据。
  • 添加代码以显示您如何发出请求、您的获取方法或您正在使用的任何内容。还要确保您没有将 API 密钥限制为特定服务。

标签: reactjs google-maps coordinates


【解决方案1】:

正如评论中正确提到的,Directions API 需要用于此目的:

路线显示为在地图上绘制路线的折线,或 另外作为元素内的一系列文本描述 (例如,“右转进入威廉斯堡桥坡道”)

以下示例演示如何将Google Maps API Directions Service 集成到google-maps-react 以显示路线。

假设data prop 包含以格式表示的坐标 在提供的问题中指定。方向服务代码已调整 来自this example

示例

class MapContainer extends React.Component {
  constructor(props) {
    super(props);
    this.handleMapReady = this.handleMapReady.bind(this);
  }

  handleMapReady(mapProps, map) {
    this.calculateAndDisplayRoute(map);
  }

  calculateAndDisplayRoute(map) {
    const directionsService = new google.maps.DirectionsService();
    const directionsDisplay = new google.maps.DirectionsRenderer();
    directionsDisplay.setMap(map);


    const waypoints = this.props.data.map(item =>{
      return{
        location: {lat: item.lat, lng:item.lng},
        stopover: true
      }
    })
    const origin = waypoints.shift().location;
    const destination = waypoints.pop().location;

    directionsService.route({
      origin: origin,
      destination: destination,
      waypoints: waypoints,
      travelMode: 'DRIVING'
    }, (response, status) => {
      if (status === 'OK') {
        directionsDisplay.setDirections(response);
      } else {
        window.alert('Directions request failed due to ' + status);
      }
    });
  }

  render() {
    return (
      <div className="map-container">
        <Map
          google={this.props.google}
          className={"map"}
          zoom={this.props.zoom}
          initialCenter={this.props.center}
          onReady={this.handleMapReady}
        />
      </div>
    );
  }
}

Demo

【讨论】:

    【解决方案2】:

    您可能想查看此页面 https://developers.google.com/maps/documentation/roads/snap

    来自该 API 调用的响应以及您已经从绘制的线条中获得的数据应该会为您提供将路径映射到道路所需的 JSON 数据。这可能不是最优雅的解决方案,因为您可能需要添加一个按钮或其他东西来计算通往道路的路线或类似的东西。

    或者,您可以在获得两个点后发出 API 调用,并在放置每个线段后更新地图。不过,这将需要大量的 API 调用。希望对您有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-23
      • 1970-01-01
      • 2013-06-23
      • 1970-01-01
      相关资源
      最近更新 更多