MapKit Annotations and User location

半世苍凉 提交于 2019-12-21 21:29:21

问题


I followed this tutorial to make my first app:

http://icodeblog.com/2009/12/21/introduction-to-mapkit-in-iphone-os-3-0/

I would really like to know how to sort the annotations in the Table in order of distance to the user (the nearest annotation is the first one on the table) How is it possible to do that?

I understand that I must use the CLLocation to find the user's location but then I have no idea.

Could any one help me?

Cheers,

Thank you in advance for your much appreciated help,

EDIT: I've added details:

the data is not in an array, it is implemented in RootViewController.m in this form:

-(void)loadOurAnnotations
{
    CLLocationCoordinate2D workingCoordinate;

    workingCoordinate.latitude = 40.763856;
    workingCoordinate.longitude = -73.973034;
    iCodeBlogAnnotation *appleStore1 = [[iCodeBlogAnnotation alloc] 

    initWithCoordinate:workingCoordinate];
    [appleStore1 setTitle:@"Apple Store 5th Ave."];
    [appleStore1 setSubtitle:@"Apple's Flagship Store"];
    [appleStore1 setAnnotationType:iCodeBlogAnnotationTypeApple];

    [mapView addAnnotation:appleStore1];

... and so on. How is it possible to do it then?

You can find the source code here:

icodeblog.com/wp-content/uploads/2009/09/iCodeMap.zip

teddafan


回答1:


On a CLLocation you can use

- (CLLocationDistance)distanceFromLocation:(const CLLocation *)location

to calculate the distance of an object from another. In this case, it would presumably be the user's current location.

If the data is in an NSArray you can use sortedArrayUsingFunction to call a helper function that calls this method.




回答2:


Loop through the CLLocations and find the distance between them and your current location.

Then use your own sorting algorithm to sort the distances you are having in an array.

for (CLLocation *loc in locations) {
  [distances addobject:[currentLocation distanceFromLocation:loc]];
}
[distances sort]; /* Own sorting algorithm */
[yourTable reloadData];


来源:https://stackoverflow.com/questions/2795100/mapkit-annotations-and-user-location

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!