Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate distance from user location to annotation when user moves

Tags:

People also ask

How to calculate distance using gps?

For this divide the values of longitude and latitude of both the points by 180/pi. The value of pi is 22/7. The value of 180/pi is approximately 57.29577951. If we want to calculate the distance between two places in miles, use the value 3, 963, which is the radius of Earth.


I have an user location (blue dot) and annotations on mapView. When annotation is selected, I setting text to distLabel - "Distance to point %4.0f m.". How can I update that text label when user moves?

didSelectAnnotationView:

- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
{

    CLLocation *pinLocation = 
      [[CLLocation alloc] initWithLatitude:
                        [(MyAnnotation*)[view annotation] coordinate].latitude 
                                 longitude:
                        [(MyAnnotation*)[view annotation] coordinate].longitude];
    CLLocation *userLocation = 
      [[CLLocation alloc] initWithLatitude:
                          self.mapView.userLocation.coordinate.latitude             
                                 longitude:
                                 self.mapView.userLocation.coordinate.longitude];        
    CLLocationDistance distance = [pinLocation distanceFromLocation:userLocation];

    [distLabel setText: [NSString stringWithFormat:@"Distance to point %4.0f m.",    
                                                     distance]];
}

I know there is a function didUpdateToLocation, but how can I use it with didSelectAnnotationView?

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{
  //Did update to location
}