Search code examples
objective-candroid-mapviewtableviewcllocation

Display the distance between a user's current location and an annotation in a Label


I want to display the distance between a user's current location and another annotation (displayed on my MapView) in a label on my custom table cell.

Each cell displays the name of a cafe (nameLabel), and underneath, I want it to display their distance away from each cafe (distanceLabel).

My MapViewController.m uses this code to calculate the distance between a user's current location and the closest cafes:

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {

    for (MapViewAnnotation *annotation in self.mapView.annotations) {
        CLLocationCoordinate2D coord = [annotation coordinate];
        CLLocation *userLocation = [[CLLocation alloc] initWithLatitude:coord.latitude longitude:coord.longitude];
        annotation.distance = [newLocation distanceFromLocation:userLocation];
        CLLocationDistance calculatedDistance = [userLocation distanceFromLocation:userLocation];
        annotation.distance = calculatedDistance;
    }

I've already set up my custom cell, I just want to know what I should put into my TableView code (TableViewController.m) in order to display the Calculated Distance inside of my text label (called distanceLabel).

E.g. how do I finish this line?

cell.distanceLabel.text = 

UPDATE

Just tried adding the reference to my TableViewController.h, but xcode keeps throwing me the error "Redefinition of 'CLLocationDistance' as different kind of symbol".

@class CLLocationDistance; 

@property (nonatomic, strong) CLLocationDistance *calculatedDistance; 

UPDATE

.h file

enter image description here

****UPDATE**

**.m file****

enter image description here


Solution

  • Make a forward reference for CLLocationDistance calculatedDistance in fx. Your .h . CLLocationDistance is typedef as a double, a prmitive data type, so don't use a pointer in your forward reference (CLLocationDistance calulatedDistance; or @property CLLocationDistance calulatedDistance;). Then do the following:

     cell.distanceLabel.text = [NSString stringWithFormat:@"%f", calculatedDistance]; 
    

    So infact you dont have to create another/new double and assign it to calculatedDistance. Sorry for any confusion..:)