50

Just a quick question on Core Location, I'm trying to calculate the distance between two points, code is below:

    -(void)locationChange:(CLLocation *)newLocation:(CLLocation *)oldLocation
    {   

    // Configure the new event with information from the location.
        CLLocationCoordinate2D newCoordinate = [newLocation coordinate];
        CLLocationCoordinate2D oldCoordinate = [oldLocation coordinate];

        CLLocationDistance kilometers = [newCoordinate distanceFromLocation:oldCoordinate] / 1000; // Error ocurring here.
        CLLocationDistance meters = [newCoordinate distanceFromLocation:oldCoordinate]; // Error ocurring here.
}

I'm getting the following error on the last two lines:

error: cannot convert to a pointer type

I've been searching Google, but I cannot find anything.

ZGski
  • 2,398
  • 1
  • 21
  • 34
Stephen
  • 4,715
  • 8
  • 53
  • 78

7 Answers7

114

Try this instead:

CLLocationDistance meters = [newLocation distanceFromLocation:oldLocation];

The method you're trying to use is a method on a CLLocation object :)

Cœur
  • 37,241
  • 25
  • 195
  • 267
deanWombourne
  • 38,189
  • 13
  • 98
  • 110
  • 11
    and also keep in my mind "This method measures the distance between the two locations by tracing a line between them that follows the curvature of the Earth" apple documents. So this won't give the distance via road. – Ankit Srivastava Dec 09 '11 at 06:32
  • 1
    how can find distance via road ? @deanWombourne – Rahul Feb 05 '15 at 12:58
  • @AnkitSrivastava how can i find the distance via road – Rahul Feb 05 '15 at 13:00
  • The easiest way would be to ask a question on stack overflow ;) Google have an API that you can use (https://developers.google.com/maps/documentation/directions/) and so do Apple (https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/LocationAwarenessPG/ProvidingDirections/ProvidingDirections.html) I guess because you're asking this on an iOS question you'll probably want the Apple one :) – deanWombourne Feb 05 '15 at 14:12
  • Good Answer, but in iOS9 this code function is taking more time than iOS8. do you have any idea how to fix? – Code Hunterr Sep 24 '15 at 07:09
  • @CodeHunterr That sounds strange - how much slower is it running? – deanWombourne Sep 24 '15 at 22:32
  • Here is time statistics: when open 200 locations it will take 2 seconds to sort all the location according to distance in iOS 8...but when you open same contacts on iOS9 it will take min 12+ seconds to sorting all the locations according to distance. – Code Hunterr Sep 25 '15 at 06:01
  • The problem might be how you are sorting your points - do you calculate the distance between each point before you sort, or do you calculate it each time you compare two points? – deanWombourne Sep 28 '15 at 14:45
  • Can you ask a question on stack overflow with your sorting code so we can see what's going on? Thanks! If you put the link in this question's comments I can take a look :) – deanWombourne Sep 28 '15 at 14:46
22

The distance is calculated between 2 CLLocations and not between to coordinates.

You need to use these coordinates to get the CLLocations for the respective coordinates using the following line of code

CLLocation *newLocation = [[CLLocation alloc] initWithCoordinate: newCoordinate altitude:1 horizontalAccuracy:1 verticalAccuracy:-1 timestamp:nil];

Similarly for the other coordinate and then you can calculate the distance between these two locations using the following line of code

CLLocationDistance kilometers = [newLocation distanceFromLocation:oldLocation] / 1000;

Hope this will help you.

Update: Swift 3.0

let distanceKiloMeters = (newLocation.distance(from: oldLocation))/1000
Atulkumar V. Jain
  • 5,102
  • 9
  • 44
  • 61
11

In Swift

Let's create a method function that calculates distance between two locations:

 func distanceBetweenTwoLocations(source:CLLocation,destination:CLLocation) -> Double{

        var distanceMeters = source.distanceFromLocation(destination)
        var distanceKM = distanceMeters / 1000
        let roundedTwoDigit = distanceKM.roundedTwoDigit
        return roundedTwoDigit

    }

If you want only two digits:

extension Double{

    var roundedTwoDigit:Double{

        return Double(round(100*self)/100)

        }
    }
Community
  • 1
  • 1
5

If you're going to do with 2 CLLocationCoordinate2D values then you can use this.

This is Swift 2.1 on Xcode 7.1

import CoreLocation

extension CLLocationCoordinate2D {

    func distanceInMetersFrom(otherCoord : CLLocationCoordinate2D) -> CLLocationDistance {
        let firstLoc = CLLocation(latitude: self.latitude, longitude: self.longitude)
        let secondLoc = CLLocation(latitude: otherCoord.latitude, longitude: otherCoord.longitude)
        return firstLoc.distanceFromLocation(secondLoc)
    }

}
Max Alexander
  • 5,471
  • 6
  • 38
  • 52
4

The problem here is that you're calling an object method:

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

of class CLLocation.

CLLocationCoordinate2D is in fact a structure, consisting of two doubles:

typedef struct
{
    CLLocationDegrees latitude;
    CLLocationDegrees longitude;
} CLLocationCoordinate2D;

Proper way of doing this is to get a CLLocation object and call distanceFromLocation on it. Like this:

CLLocation* newLocation;
CLLocation* oldLocation;
CLLocationDistance distance = [newLocation distanceFromLocation:oldLocation];

Of course you first need to initialize both of those values (from CLLocationManager, for instance).

Atulkumar V. Jain
  • 5,102
  • 9
  • 44
  • 61
Pawel
  • 4,699
  • 1
  • 26
  • 26
4
#import <CoreLocation/CoreLocation.h>

CLLocation *locA = [[CLLocation alloc] initWithLatitude:"Value" longitude:"Value"];

CLLocation *locB = [[CLLocation alloc] initWithLatitude:"Value" longitude:"Value"];

CLLocationDistance distance = [locA distanceFromLocation:locB];
NSLog(@"distance:-%f",distance);//distance in Miter
  • Need explanation for this answer – Burhanuddin Rashid Sep 29 '16 at 05:28
  • Hi Burhanuddin Rashid This is not Android Development code. it is ios Development code for the "Calculate distance between two points" – Yogesh Tarsariya Sep 30 '16 at 11:57
  • It doesn't matter weather its IOS,Android or any other Technical Field. The Think is answer should have little bit explanation with the code...just don't copy paste the code..please have courtesy for some explaination – Burhanuddin Rashid Sep 30 '16 at 12:05
  • Hi Burhanuddin Rashid this answer is not copy and past. it is apple default function to get Distance. my answer is little but its work perfectly. you enter locA enter Lat,long locB enter Lat,long to Calculate distance in LocA to LocB. More information[link](https://developer.apple.com/reference/corelocation/cllocationmanager) thanks.. – Yogesh Tarsariya Oct 01 '16 at 07:06
2

Taken from the excellent libary CoreLocation utitlities :

- (CLLocationDistance) distanceFromCoordinate:(CLLocationCoordinate2D) fromCoord;
{
    double earthRadius = 6371.01; // Earth's radius in Kilometers

    // Get the difference between our two points then convert the difference into radians
    double nDLat = (fromCoord.latitude - self.coordinate.latitude) * kDegreesToRadians;  
    double nDLon = (fromCoord.longitude - self.coordinate.longitude) * kDegreesToRadians; 

    double fromLat =  self.coordinate.latitude * kDegreesToRadians;
    double toLat =  fromCoord.latitude * kDegreesToRadians;

    double nA = pow ( sin(nDLat/2), 2 ) + cos(fromLat) * cos(toLat) * pow ( sin(nDLon/2), 2 );

    double nC = 2 * atan2( sqrt(nA), sqrt( 1 - nA ));
    double nD = earthRadius * nC;

    return nD * 1000; // Return our calculated distance in meters
}
zerodog
  • 568
  • 4
  • 11