Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
461 views
in Technique[技术] by (71.8m points)

ios - latitude and longitude points from MKPolyline

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 store latitude and longitude points, but I am looking for a way to build an array of lat and long the MKPolyline would touch on the map.

Anybody has specific possible solutions on this?

Thank you

EDIT: After seeing the first response (thank you) I think I need to explain better what my code is doing:

  1. first I call "calculateDirectionsWithCompletionHandler" on a MKDirections object
  2. I get back MKRoute object which has a "polyline" property.
  3. then I call "addOverlay" on the mapview passing in the polyline from the MKRoute object

That's all.

So, I already have a polyline built for me. So I would like to get all the points found in the polyline somehow and map them to a lat and long...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...