Calculate lat/long coords a specific distance away from another pair of lat/long coords [duplicate]

↘锁芯ラ 提交于 2019-12-04 13:45:46
Morgan Chen

The set of points a fixed distance from a central point has infinite members, so it's not possible to list out every one. However, given a single point you could check if it is within the set by using the distanceFromLocation: method.

Mathematically, given a radius coordinate (long, lat) and assuming the Earth is flat, the equation of the circle with radius (distance) r would be

r^2 = (x - long)^2 + (y - lat)^2

With the use of some magic, this becomes

x = r cosθ - long; y = r sinθ - lat

So now you can punch in any arbitrary angle and for a known distance/radius get a point on the edge of the circle. In map terms, the angle 0 will give you the point on the circle straight east of the center. Positive angles go counterclockwise around the center.

In code:

-(CLLocation*)locationForAngle:(float)angle fromCenterLocation:(CLLocation *)center withDistance:(float)distance {
    //angle must be in radians
    float longitude = distance * cosf(angle) - center.coordinate.longitude;
    float latitude = distance * sinf(angle) - center.coordinate.latitude;
    return [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
}

Edit: I accidentally dropped a few terms

Anthony

I found my answer on this link Moving a CLLocation by x meters and ported it to work with Swift.

func locationWithBearing(bearing: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(bearing))
    let lon2 = lon1 + atan2(sin(bearing) * 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!