我有固定位置的纬度和经度。我想检查另一个位置(纬度和经度)是否足够靠近固定位置(50-100米)。我使用iPhone获取当前位置。
答案 0 :(得分:14)
CLLocation 的方法– distanceFromLocation:正是您所需要的。
答案 1 :(得分:7)
distanceFromCurrentLocation = [userLocation distanceFromLocation:destinationlocation]/convertToKiloMeter;
if(distanceFromCurrentLocation < 100 && distanceFromLocation > .500)
{
NSLog(@"Yeah, this place is inside my circle");
}
else
{
NSLog(@"Oops!! its too far");
}
这可以找到空中距离,或者我们可以说是直线距离 希望你不要寻找道路距离。
答案 2 :(得分:1)
CLLocation *location;// = init...;
double distance = [location distanceFromLocation:otherLoc]; //in meters
答案 3 :(得分:1)
虽然我Upvoted Empty Stack答案.. 如果您需要更多帮助,请参阅代码..
成为CLLocationManagerDelegate,然后在您的实现类中。
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
int distance = [newLocation distanceFromLocation:oldLocation];
if(distance >50 && distance <100)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Distance"
message:[NSString stringWithFormat:@"%i meters",distance]
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
}
}
}
答案 4 :(得分:1)
添加到Deepukjayan的答案,使用CLLocation在使用他的答案之前定义引用:
CLLocation *montreal = [[CLLocation alloc] initWithLatitude:45.521731 longitude:-73.628679];
答案 5 :(得分:0)
func distance(from location: CLLocation) -> CLLocationDistance
答案 6 :(得分:0)
这是在Swift中使用CoreLocation进行操作的方法。您只需使用.distance(from: )
类型的CLLocation
方法比较两个不同的位置。确保两个位置的类型均为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
}
这不是必需的,但也许您需要保存经纬度,以便以后进行其他比较。我知道我需要他们
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)