31

我正在尝试找出一种方法来从 iOS 应用程序上的 MKMapView 上绘制的 MKPolyline 获取所有纬度和经度点。

我知道 MKPolyline 不存储纬度和经度点,但我正在寻找一种方法来构建 MKPolyline 将在地图上触及的纬度和经度数组。

有人对此有具体的可能解决方案吗?

谢谢

编辑:看到第一个响应(谢谢)后,我想我需要更好地解释我的代码在做什么:

  1. 首先我在 MKDirections 对象上调用“ calculateDirectionsWithCompletionHandler ”
  2. 我取回具有“折线”属性的MKRoute对象。
  3. 然后我在从 MKRoute对象传入折线的地图视图上调用“ addOverlay

就这样。

所以,我已经为我构建了一条折线。所以我想以某种方式获取折线中找到的所有点并将它们映射到经纬度......

4

2 回答 2

51

要从 获取折线的坐标MKRoute,请使用getCoordinates:range:方法。
该方法在继承自的MKMultiPoint类中。MKPolyline

这也意味着这适用于任何折线——无论它是由您创建还是由MKDirections.

您分配一个足够大的 C 数组以容纳所需的坐标数并指定范围(例如,从第 0 个开始的所有点)。

例子:

//route is the MKRoute in this example
//but the polyline can be any MKPolyline

NSUInteger pointCount = route.polyline.pointCount;

//allocate a C array to hold this many points/coordinates...
CLLocationCoordinate2D *routeCoordinates 
    = malloc(pointCount * sizeof(CLLocationCoordinate2D));

//get the coordinates (all of them)...
[route.polyline getCoordinates:routeCoordinates 
                         range:NSMakeRange(0, pointCount)];

//this part just shows how to use the results...
NSLog(@"route pointCount = %d", pointCount);
for (int c=0; c < pointCount; c++)
{
    NSLog(@"routeCoordinates[%d] = %f, %f", 
        c, routeCoordinates[c].latitude, routeCoordinates[c].longitude);
}

//free the memory used by the C array when done with it...
free(routeCoordinates);

根据路线,为数百或数千个坐标做好准备。

于 2014-02-18T21:14:48.957 回答
21

斯威夫特 3 版本:

我知道这是一个非常古老的问题,但在搜索此问题时,它仍然是 Google 上的热门话题之一,没有好的 Swift 解决方案,所以想分享我的小扩展,通过添加coordinates属性让生活更轻松到 MKPolyline:

https://gist.github.com/freak4pc/98c813d8adb8feb8aee3a11d2da1373f

于 2017-02-12T11:01:55.050 回答