Distancefromlocation - Calculate Distance Between Two Points

How to find out distance between coordinates?

CLLocation has a distanceFromLocation method so given two CLLocations:

CLLocationDistance distanceInMeters = [location1 distanceFromLocation:location2];

or in Swift 4:

//: Playground - noun: a place where people can play

import CoreLocation


let coordinate₀ = CLLocation(latitude: 5.0, longitude: 5.0)
let coordinate₁ = CLLocation(latitude: 5.0, longitude: 3.0)

let distanceInMeters = coordinate₀.distance(from: coordinate₁) // result is in meters

you get here distance in meter so 1 miles = 1609 meter

if(distanceInMeters <= 1609)
{
// under 1 mile
}
else
{
// out of 1 mile
}

distanceFromLocation - Calculate distance between two points

Try this instead:

CLLocationDistance meters = [newLocation distanceFromLocation:oldLocation];

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

Calculating Distance between two coordinates using CLLocation

The error you're getting is actually:

Initializing 'CLLocationDistance *' (aka 'double *') with an expression of incompatible type 'CLLocationDistance' (aka 'double')

What it's saying is you're initializing itemDist (which you've declared as a CLLocationDistance *) to something that is returning a CLLocationDistance (notice no asterisk).

CLLocationDistance is not an object.

It is just a primitive type (specifically double -- see the Core Location Data Types Reference).



So instead of declaring itemDist as a pointer to a CLLocationDistance, just declare it as a CLLocationDistance (no asterisk):

CLLocationDistance itemDist = [itemLoc distanceFromLocation:current];

You'll also need to update the NSLog to expect a double instead of an object otherwise it will crash at run-time:

NSLog(@"Distance: %f", itemDist);

Finding distance between CLLocationCoordinate2D points

You should create an object of CLLocation using,

- (id)initWithLatitude:(CLLocationDegrees)latitude
longitude:(CLLocationDegrees)longitude;

Then, you should be able to calculate the distance using

[location1 distanceFromLocation:location2];

Distance between 2 points with CLLocationCoordinate2D

Use the below method for finding distance between two locations

-(float)kilometersfromPlace:(CLLocationCoordinate2D)from andToPlace:(CLLocationCoordinate2D)to  {

CLLocation *userloc = [[CLLocation alloc]initWithLatitude:from.latitude longitude:from.longitude];
CLLocation *dest = [[CLLocation alloc]initWithLatitude:to.latitude longitude:to.longitude];

CLLocationDistance dist = [userloc distanceFromLocation:dest]/1000;

//NSLog(@"%f",dist);
NSString *distance = [NSString stringWithFormat:@"%f",dist];

return [distance floatValue];

}

how to get the distance between two locations in miles in objective c?

This has already been answered in metric here. Now you just need to convert meters to miles which is:

1 Meter = 0.000621371192 Miles 

or

1 Mile = 1609.344 Meters 


Related Topics



Leave a reply



Submit