获取从纬度/经度点沿折线的距离 [英] Get distance along polyline from lat/lng point

查看:133
本文介绍了获取从纬度/经度点沿折线的距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用如下所示的数据在Google地图上绘制一条折线:

I'm rendering a polyline on a Google map with data that looks like this:

data = [
  {
    distance: 3.45,
    lat: 37.37112776376307,
    lng: -122.13909476995468,
  },
  ...
];

将鼠标悬停在折线上时,我可以获取lat/lng坐标,并希望基于这些坐标获取沿线的距离.

When hovering over the polyline, I can get the lat/lng coordinates and I want to get the distance along the line based on those coordinates.

我还没有找到使用Maps API的简单方法.我想要从起点到任意点的距离沿着折线;我发现的大多数答案都只涉及两点之间(最短的)距离,而不是沿预定的路线.

I haven't found an easy way to do this with the Maps API. I want the distance from the start to an arbitrary point along the polyline; most answers I've found deal simply with the (shortest) distance between two points, not along a predefined route.

我的另一个想法是使用D3(我正在使用它绘制一些相关的图表)将数据一分为二并获取距离.但是,我无法弄清楚如何根据两个数据点(lat + lng)进行二等分.

My other thought was to use D3 (which I'm using to draw some related charts) to bisect the data and get the distance. However, I can't figure out how to bisect based on two data points (lat+ lng).

关于如何完成我要完成的工作的任何建议吗?

Any advice on how to accomplish what I'm trying to do?

在我的数据中,distance是在给定坐标处的累计距离.

In my data, distance is the cumulative distance traveled at the given coordinates.

推荐答案

我想我希望Maps API的方法类似于

I guess I was hoping the Maps API would have a method along the lines of

polyLine.computeDistanceBetween(point1, point2);

但事实并非如此.

我最终解决了类似于@Mark_M上面描述的问题的问题:

I ended up breaking down the problem similar to how @Mark_M describes above:

  1. 在折线上找到最接近悬停点的点

function getIndexOfNearestPoint(path, hoveredPoint) {
  let index = -1;
  let minDistance = 1000;

  path.forEach((pointOnPath, idx) => {
    const dist = window.google.maps.geometry.spherical.computeDistanceBetween(
      hoveredPoint,
      pointOnPath
    );

    if (dist < minDistance){
      minDistance = dist;
      index = idx;
    }
  });

  return index;
}

  • 计算折线上2个点之间的距离

  • Calculate the distance between 2 points on the polyline

    function getDistanceAlongPath(path, startIndex, endIndex) {
      let distance = 0;
      for (let ii = startIndex; ii < endIndex; ii++) {
        distance += window.google.maps.geometry.spherical.computeDistanceBetween(
          path[ii],
          path[ii + 1]
        );
      }
      return distance;
    }
    

  • 将其放在一起以找到从折线起点到悬停点的累计距离:

    Putting it together to find the cumulative distance from the start of the polyline to the hovered point:

    polyline.addListener('mousemove', e => {
      const path = polyline.getPath().getArray();
      const hoveredPoint = e.latLng;
      const startIndex = 0;
    
      const endIndex = getIndexOfNearestPoint(path, hoveredPoint);
      const distance = getDistanceAlongPath(path, startIndex, endIndex);
    });
    

    这篇关于获取从纬度/经度点沿折线的距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆