Reputation: 43
Good day, I'm fairly new to Objective C Dev and am enquiring to an implementation of the midpoint formula located here http://www.movable-type.co.uk/scripts/latlong.html.
Formula:
Bx = cos(lat2).cos(Δlong)
By = cos(lat2).sin(Δlong)
latm = atan2(sin(lat1) + sin(lat2), √((cos(lat1)+Bx)² + By²))
lonm = lon1 + atan2(By, cos(lat1)+Bx)
My Implementation of this formula in Objective C is.
- (CLLocationCoordinate2D) getMidPointCoords
{
double dLon = (self.toCoordinate.longitude - self.fromCoordinate.longitude) * (M_PI/180);
double Bx = cos(self.toCoordinate.latitude)*cos(dLon);
double By = cos(self.toCoordinate.latitude)*sin(dLon);
double latM = atan2(sin(self.fromCoordinate.latitude)+sin(self.toCoordinate.latitude), sqrt( (cos(self.fromCoordinate.latitude)+Bx)*(cos(self.fromCoordinate.latitude)+Bx) + By*By) );
double lonM = self.fromCoordinate.longitude + atan2(By, cos(self.fromCoordinate.latitude) + Bx);
CLLocationCoordinate2D midPoint;
midPoint.latitude = latM;
midPoint.longitude = lonM;
}
When I debug this code though it is clearly returning the incorrect coordinates. So essentially my Question is "Is this because of the fact that I am using doubles?" or is my implementation of this formula simply flauwed?
Thank you in advance to any assistance, or insight provided.
Upvotes: 1
Views: 548
Reputation:
The trigonometric functions you are using (sin
, cos
, atan2
) require their parameter to be in radians, not degrees.
For example, in this line:
double Bx = cos(self.toCoordinate.latitude)*cos(dLon);
the cos(self.toCoordinate.latitude)
is wrong because self.toCoordinate.latitude
is in degrees but cos
requires radians.
Everywhere that you call a trigonometric function, first convert the parameter from degrees to radians (multiply degrees by (M_PI/180.0)
).
In addition, in this line:
double lonM = self.fromCoordinate.longitude + atan2(...
the self.fromCoordinate.longitude
also needs to be converted to radians because the rest of the expression is also in radians.
Finally, at the end latM
and lonM
will have the midpoint but in radians (not degrees).
So when setting midPoint.latitude
and midPoint.longitude
, you have to convert latM
and lonM
from radians back to degrees by multiplying them by (180.0/M_PI)
.
Upvotes: 1