This question already has an answer here:
- Moving a CLLocation by x meters 10 answers
My app needs to be able to get the user starting location and then calculate lat/long coords specific distances away from that spot (in all directions). Does anyone know how I might accomplish this?
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
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.
来源:https://stackoverflow.com/questions/26490313/calculate-lat-long-coords-a-specific-distance-away-from-another-pair-of-lat-long