ios - 在固定点和我在 iOS 中的当前位置之间行走时计算距离
<p><p>我必须计算 iOS 和 objective-c中两个位置之间的距离。我的一个位置固定在一个点上,当我走路时,我必须计算我当前位置和固定点之间的距离。我使用了 <strong>distanceFromLocation</strong> 方法,但我没有得到更近的距离值。我浏览了几篇文章和一些 StackOverflow 解决方案,但没有一个给出正确的结果。</p>
<p>下面是我使用的代码,代码中的 currentLocation 和 destinationLocation 是保存位置纬度和经度的属性。 destinationLocation 始终是一个固定位置,并且当我走路时 currentLocation 不断变化。很少有 UILabel 可以打印当前和固定的纬度和经度值。我必须每次计算这两点之间的距离。当我移动半米或更少米时,它会显示很长的距离,这也是不一致的。你能帮我看看我在这里犯了什么错误吗?有没有其他方法可以实现这一目标?谢谢!</p>
<pre><code>- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
CLLocation *newLocation = locations.lastObject;
self.currentLocation = [ initWithLatitude:newLocation.coordinate.latitude longitude:newLocation.coordinate.longitude];
if(self.destinationLocation == nil){
self.destinationLocation = [ initWithLatitude:newLocation.coordinate.latitude longitude:newLocation.coordinate.longitude];
self.destinationLatitude.text = ;
self.destinationLongitude.text = ;
}
self.currentLatitude.text = ;
self.currentLongitude.text = ;
CLLocationDistance distance = ;
self.gpsDistanceMeasurement.text = ;
}
</code></pre></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>你可以使用haversine公式计算两点之间的距离</p>
<p><strong>swift 3.x</strong></p>
<pre><code>let Source = CLLocationCoordinate2D.init(latitude: lat, longitude: long)
let Destination = CLLocationCoordinate2D.init(latitude: lat, longitude: long)
func DistanceCalculator(Source:CLLocationCoordinate2D,Destination:CLLocationCoordinate2D) -> Double
{
// HaverSine Formula to calculate Diastance On Sphere Refrences//https://www.movable-type.co.uk/scripts/latlong.html
// Angle = sin2(∆Ø/2) + cosØ1 * cosØ2 * sin2(∆ø/2)
// constant = 2 * atan2(√angle,√1-angle)
// distance = R * c
let Earth_Radius:Double = 6371 * 1000
let LatDelta = self.DegreeToRad(Degree: (Destination.latitude - Source.latitude))
let LongDelta = self.DegreeToRad(Degree: (Destination.longitude - Source.longitude))
let latRad = self.DegreeToRad(Degree: Source.latitude)
let longRad = self.DegreeToRad(Degree: Destination.latitude)
let Angle = (sin(LatDelta/2) * sin(LatDelta/2)) + (cos(latRad) * cos(longRad) * sin(LongDelta/2) * sin(LongDelta/2))
let constant = 2 * atan2(sqrt(Angle),sqrt(1-Angle))
let Distance = Earth_Radius * constant
return Distance
}
func DegreeToRad(Degree:Double) -> Double
{
return Degree * (Double.pi / 180)
}
</code></pre></p>
<p style="font-size: 20px;">关于ios - 在固定点和我在 iOS 中的当前位置之间行走时计算距离,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/51136210/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/51136210/
</a>
</p>
页:
[1]