How to check if current coordinates are within a radius of other coordinates
Solution 1
The method – distanceFromLocation: of CLLocation is exactly what you need.
Solution 2
distanceFromCurrentLocation = [userLocation distanceFromLocation:destinationlocation]/convertToKiloMeter;
if(distanceFromCurrentLocation < 100 && distanceFromLocation > .500)
{
NSLog(@"Yeah, this place is inside my circle");
}
else
{
NSLog(@"Oops!! its too far");
}
This finds the air distance, or we can say, straight line distance only.
Hope you are not looking for road distance.
Solution 3
Here's how to do it in Swift using CoreLocation. You just compare 2 different locations using the .distance(from: )
method on a location that is of type CLLocation
. Make sure both locations are of type CLLocation
import CoreLocation
let someOtherLocation: CLLocation = CLLocation(latitude: someOtherLat,
longitude: someOtherLon)
guard let usersCurrentLocation: CLLocation = locationManager.location else { return }
// **the distance(from: ) is right here **
let distanceInMeters: CLLocationDistance = usersCurrentLocation.distance(from: someOtherLocation)
if distanceInMeters < 100 {
// this user is pretty much in the same area as the otherLocation
} else {
// this user is at least over 100 meters outside the otherLocation
}
this isn't necessary but maybe you need to save the lats and lons for later for another comparison. I know I needed them
let usersCurrentLat: CLLocationDegrees = currentLocation.coordinate.latitude // not neccessary but this is how you get the lat
let usersCurrentLon: CLLocationDegrees = currentLocation.coordinate.longitude // not neccessary but this is how you get the lon
let someOtherLocationLat: CLLocationDegrees = someOtherLocationLocation.coordinate.latitude // not neccessary but this is how you get the lat
let someOtherLocationLon: CLLocationDegrees = someOtherLocationtLocation.coordinate.longitude // not neccessary but this is how you get the lon
let usersLocation: CLLocation = CLLocation(latitude: usersCurrentLat,
longitude: usersCurrentLon)
let otherLocation: CLLocation = CLLocation(latitude: someOtherLocationLat,
longitude: someOtherLocationLon)
Solution 4
CLLocation *location;// = init...;
double distance = [location distanceFromLocation:otherLoc]; //in meters
Solution 5
Adding to Deepukjayan answer, use CLLocation to define a reference before using his answer:
CLLocation *montreal = [[CLLocation alloc] initWithLatitude:45.521731 longitude:-73.628679];
Related videos on Youtube
1110
Updated on June 04, 2022Comments
-
1110 over 1 year
I have latitude and longitude of a fixed location. I want to check if another location (latitude and longitude) is close enough (50-100 meters) to the fixed location. I use iPhone to get current location.