Anthony - 2 months ago 30

Swift Question

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?

Answer

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