latitude and longitude points from MKPolyline

前端 未结 2 1455
北荒
北荒 2020-12-09 08:00

I am trying to figure out a way to get all the latitude and longitude points from a MKPolyline drawn on a MKMapView on an iOS app.

I know the MKPolyline does not sto

相关标签:
2条回答
  • 2020-12-09 08:38

    To get coordinates of the polyline from an MKRoute, use the getCoordinates:range: method.
    That method is in the MKMultiPoint class which MKPolyline inherits from.

    That also means this works for any polyline -- whether it was created by you or by MKDirections.

    You allocate a C array big enough to hold the number of coordinates you want and specify the range (eg. all points starting from the 0th).

    Example:

    //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);
    

    Depending on the route, be prepared for hundreds or thousands of coordinates.

    0 讨论(0)
  • 2020-12-09 08:57

    Swift 3 version:

    I'm aware this is a very old question, but its still one of the top hits on Google when searching for this issue, with no good Swift solutions, So wanted to share my tiny extension to make life a bit easier by adding a coordinates property to MKPolyline:

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

    0 讨论(0)
提交回复
热议问题