Moving a CLLocation by x meters

前端 未结 11 984
余生分开走
余生分开走 2020-11-30 04:54

I have a CLLocation defined, and I\'d like to move that point x meters to the east and y meters to the south. How may I achieve that?

11条回答
  •  生来不讨喜
    2020-11-30 05:29

    Swift 4.2 as a CGPoint extension

    Derived from Peter O.'s solution

    FloatingPoint extension: thanks to https://stackoverflow.com/a/29179878/2500428

    extension FloatingPoint
    {
        var degreesToRadians: Self { return self * .pi / 180 }
        var radiansToDegrees: Self { return self * 180 / .pi }
    }
    
    extension CGPoint
    {
        // NOTE: bearing is in radians
        func locationWithBearing(bearing: Double, distanceMeters: Double) -> CGPoint
        {
            let distRadians = distanceMeters / (6372797.6) // earth radius in meters
    
            let origLat = Double(self.y.degreesToRadians)
            let origLon = Double(self.x.degreesToRadians)
    
            let newLat = asin(sin(origLat) * cos(distRadians) + cos(origLat) * sin(distRadians) * cos(bearing))
            let newLon = origLon + atan2(sin(bearing) * sin(distRadians) * cos(origLat), cos(distRadians) - sin(origLat) * sin(newLat))
    
            return CGPoint(x: newLon.radiansToDegrees, y: newLat.radiansToDegrees)
        }
    }
    

    Usage:

    let loc = CGPoint(x: lon, y: lat)
    let newLoc = loc.locationWithBearing(bearing: 90.degreesToRadians, distanceMeters: 500.0)
    

提交回复
热议问题