Moving a CLLocation by x meters

A conversion to Swift, taken from this answer:

func locationWithBearing(bearingRadians:Double, distanceMeters:Double, origin:CLLocationCoordinate2D) -> CLLocationCoordinate2D {
    let distRadians = distanceMeters / (6372797.6) // earth radius in meters

    let lat1 = origin.latitude * M_PI / 180
    let lon1 = origin.longitude * M_PI / 180

    let lat2 = asin(sin(lat1) * cos(distRadians) + cos(lat1) * sin(distRadians) * cos(bearingRadians))
    let lon2 = lon1 + atan2(sin(bearingRadians) * sin(distRadians) * cos(lat1), cos(distRadians) - sin(lat1) * sin(lat2))

    return CLLocationCoordinate2D(latitude: lat2 * 180 / M_PI, longitude: lon2 * 180 / M_PI)
}

Morgan Chen wrote this:

All of the math in this method is done in radians. At the start of the
method, lon1 and lat1 are converted to radians for this purpose as
well. Bearing is in radians too. Keep in mind this method takes into
account the curvature of the Earth, which you don’t really need to do
for small distances.

My comments (Mar. 25, 2021):

The calculation used in this method is called solving the “direct geodesic problem”, and this is discussed in C.F.F. Karney’s article “Algorithms for geodesics”, 2012. The code given above uses a technique that is less accurate than the algorithms presented in Karney’s article.

Leave a Comment

tech