Calculating Distance between two coordinates using CLLocation

后端 未结 4 1439
南方客
南方客 2021-01-13 12:03

I\'m using CLLocationDistance to get the distance between two points, but I\'m getting an error when passing my current location in it.

CLLocati         


        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-13 12:30

    Below code will work for you in view load

    //************************** GEtting USer's latitude/ Longitude ********************
    
    
    
    
      self.locationManager = [[CLLocationManager alloc] init];
            self.locationManager.delegate = self;
            [self.locationManager startUpdatingLocation];
    //************************** GEtting USer's latitude/ Longitude ********************
    

    pragma mark - CLLocationManagerDelegate

    - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
    {
        NSLog(@"didFailWithError: %@", error);
        UIAlertView *errorAlert = [[UIAlertView alloc]
                                   initWithTitle:@"Error" message:@"Failed to Get Your Location" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [errorAlert show];
    }
    - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
    {
        NSLog(@"didUpdateToLocation: %@", newLocation);
        CLLocation *currentLocation = newLocation;
        if (currentLocation != nil) {        
            CLLocation *locA = [[CLLocation alloc] initWithLatitude:currentLocation.coordinate.longitude longitude:currentLocation.coordinate.latitude];
            CLLocation *locB = [[CLLocation alloc] initWithLatitude:11.111111111111111 longitude:11.1111111111111111]; 
            User_Vanue_Distance = [locA distanceFromLocation:locB];
            NSLog(@"THIS IS THE DISTANCE BT TWO POINTS +++++++++++++++++++++%f",User_Vanue_Distance);  
        }
    }
    

    You need to put below keys in info.plist, in ios 8 to access location we need to put below keys in info.plist 1. NSLocationWhenInUseUsageDescription : Location required 2. NSLocationAlwaysUsageDescription Needed : Location Needed

    This will work for you but one thing you need to add is add a check for ios8. otherwise this will crash on ios 7

    // Check for iOS 8. Without this guard the code will crash with "unknown selector" on iOS 7.
    
    
      if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
            [self.locationManager requestWhenInUseAuthorization];
        }
    

    Hope this will work for you. :)

提交回复
热议问题