如何找出坐标之间的距离?
我想让它显示两个CLLocation坐标之间的距离。 有没有一个复杂的math公式做到这一点? 如果没有一个公式你会怎么做?
CLLocation有一个distanceFromLocation方法,所以有两个CLLocations:
CLLocationDistance distanceInMeters = [location1 distanceFromLocation:location2];
或者在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
你在这里得到的距离 ,所以1英里 = 1609米
if(distanceInMeters <= 1609) { // under 1 mile } else { // out of 1 mile }
试试这个:
distanceInMeters = fromLocation.distanceFromLocation(toLocation) distanceInMiles = distanceInMeters/1609.344
来自Apple文档 :
返回值:两个位置之间的距离(以米为单位)。
您可以使用distanceFromLocation
来查找两个坐标之间的距离。
代码片段:
CLLocation *loc1 = [[CLLocation alloc] initWithLatitude:lat1 longitude:lng1]; CLLocation *loc2 = [[CLLocation alloc] initWithLatitude:lat2 longitude:lng2]; CLLocationDistance distance = [loc1 distanceFromLocation:loc2];
你的输出将以米为单位。