来自MKPolyline的纬度和经度点

时间:2014-02-18 17:42:53

标签: ios mkmapview mkpolyline

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

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

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

谢谢

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

  1. 首先我在MKDirections对象上调用“ calculateDirectionsWithCompletionHandler
  2. 我找回 MKRoute 对象,该对象具有“折线”属性。
  3. 然后我在mapview上调用“ addOverlay 从MKRoute传递折线对象
  4. 就是这样。

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

2 个答案:

答案 0 :(得分:51)

要从MKRoute获取折线的坐标,请使用getCoordinates:range:方法 该方法位于MKMultiPointMKPolyline继承自。

这也意味着这适用于任何折线 - 无论是由您创建还是由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);

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

答案 1 :(得分:15)

Swift 3版本:

我知道这是一个非常古老的问题,但它仍然是Google搜索此问题时最受欢迎的问题之一,没有好的Swift解决方案,所以我想分享我的小扩展,让生活变得更轻松向MKPolyline添加coordinates属性:

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

相关问题