计算从纬度/经度坐标到街道的距离

时间:2014-05-01 07:05:19

标签: ios math geolocation

我有一条街道的坐标,例如:

CLLocationCoordinate2D street[3];
street[0] = CLLocationCoordinate2DMake(-17.3521, 145.5898);
street[1] = CLLocationCoordinate2DMake(-17.3518, 145.5910);
street[2] = CLLocationCoordinate2DMake(-17.3515, 145.5917);

位置相当靠近街道(约60米):

CLLocationCoordinate2D location = CLLocationCoordinate2DMake(-17.3525, 145.5911);

如何计算沿街道路径的位置和位置之间的距离?

我没有找到距离阵列中最近点的距离,我希望距离到点之间的最近位置。

修改

用图片描述我的问题更容易:

whats going on

  • street是三个红点
  • location是蓝点

我想以米为单位计算黄线的长度。

3 个答案:

答案 0 :(得分:0)

请看一下这个网站:link

它显示了不同类型的距离测量与纬度和经度坐标甚至一些代码示例(在javascript中)。

答案 1 :(得分:0)

如果您找到两个位置之间的乌鸦距离,请将CLLocation对象设为两个坐标,然后

CLLocationDistance meters = [newLocation distanceFromLocation:oldLocation];

如果你发现实际的道路距离将两根弦线分成几条直线并找到距离并加起来。

答案 2 :(得分:0)

我试图解决这个问题,但我不确定这是不是最好的方式?

// http://www.cprogramto.com/c-program-to-find-shortest-distance-between-point-and-line-segment/
double FindDistanceToSegment(double x1, double y1, double x2, double y2, double pointX, double pointY)
{
  double diffX = x2 - x1;
  float diffY = y2 - y1;
  if ((diffX == 0) && (diffY == 0))
  {
    diffX = pointX - x1;
    diffY = pointY - y1;
    return sqrt(diffX * diffX + diffY * diffY);
  }

  float t = ((pointX - x1) * diffX + (pointY - y1) * diffY) / (diffX * diffX + diffY * diffY);

  if (t < 0)
  {
    //point is nearest to the first point i.e x1 and y1
    diffX = pointX - x1;
    diffY = pointY - y1;
  }
  else if (t > 1)
  {
    //point is nearest to the end point i.e x2 and y2
    diffX = pointX - x2;
    diffY = pointY - y2;
  }
  else
  {
    //if perpendicular line intersect the line segment.
    diffX = pointX - (x1 + t * diffX);
    diffY = pointY - (y1 + t * diffY);
  }

  //returning shortest distance
  return sqrt(diffX * diffX + diffY * diffY);
}

-

CLLocationCoordinate2D street[3];
street[0] = CLLocationCoordinate2DMake(-17.3521, 145.5898);
street[1] = CLLocationCoordinate2DMake(-17.3518, 145.5910);
street[2] = CLLocationCoordinate2DMake(-17.3515, 145.5917);

CLLocationCoordinate2D location = CLLocationCoordinate2DMake(-17.3525, 145.5911);


CLLocationDegrees distanceDegrees = CGFLOAT_MAX;
for (NSUInteger nodeIndex = 1; nodeIndex < 3; nodeIndex++) {
  CLLocationCoordinate2D nodeCoord = street[nodeIndex];
  CLLocationCoordinate2D prevNodeCoord = street[nodeIndex - 1];

  CLLocationDegrees distanceToCurrent = FindDistanceToSegment(prevNodeCoord.longitude, prevNodeCoord.latitude, nodeCoord.longitude, nodeCoord.latitude, location.longitude, location.latitude);

  if (distanceToCurrent < distanceDegrees)
    distanceDegrees = distanceToCurrent;
}

CLLocationDistance distance = distanceDegrees * 111111; // 1.0 degree is approximately 111,111 meters

NSLog(@"%f", distance);  // 78.15 meters