Find the mid point between two CLLocationCoordinate2D when going over 180 degrees

896 Views Asked by At

I have the following code to work out the MKCoordinateRegion to display the map including two defined points. The problem is it doesn't work when the longitude goes over 180 or -180 degrees.

CLLocationCoordinate2D tempPoint1 = CLLocationCoordinate2DMake(startLat,startLong);
CLLocationCoordinate2D tempPoint2 = CLLocationCoordinate2DMake(nextLat,nextLong);

if (lineType == 1) {
    [self createGreatCircleMKPolylineFromPoint: tempPoint1 toPoint: tempPoint2 forMapView:mapView];
}
else  {
    CLLocationCoordinate2D *coords = malloc(sizeof(CLLocationCoordinate2D) * 2);
    coords[0] = tempPoint1;
    coords[1] = tempPoint2;

    MKPolyline *polyline = [MKPolyline polylineWithCoordinates:coords count:2];
    free(coords);
    [mapView addOverlay:polyline];

}

double lon1 = tempPoint1.longitude * M_PI / 180;
double lon2 = tempPoint2.longitude * M_PI / 180;

double lat1 = tempPoint1.latitude * M_PI / 180;
double lat2 = tempPoint2.latitude * M_PI / 180;

double dLon = lon2 - lon1;

double x = cos(lat2) * cos(dLon);
double y = cos(lat2) * sin(dLon);

double lat3 = atan2( sin(lat1) + sin(lat2), sqrt((cos(lat1) + x) * (cos(lat1) + x) + y * y) );
double lon3 = lon1 + atan2(y, cos(lat1) + x);

CLLocationCoordinate2D center;

center.latitude  = lat3 * 180 / M_PI;
center.longitude = lon3 * 180 / M_PI;


MKCoordinateSpan locationSpan;
locationSpan.latitudeDelta = fabs(tempPoint1.latitude - tempPoint2.latitude) * 1.2;
locationSpan.longitudeDelta = fabs(tempPoint1.longitude - tempPoint2.longitude) * 1.2;
MKCoordinateRegion region = {center, locationSpan};

[mapView setRegion:region];

Any ideas how I could alter this code to make sure it can handle the startLong being positive i.e. 174 and the nextLong being negative i.e. -127, and vice versa

1

There are 1 best solutions below

2
On

As startLong and nextLong are longitude in degrees, so from 0° to 360°, you can make sure they are both positive and nextLong >= startLong:

while( startLong < 0.0 ) startLong += 360.0f;
while( startLong >= 360.0 ) startLong -= 360.0f;
while( nextLong < startLong ) nextLong += 360.0f;
while( nextLong - startLong > 360.0 ) nextLong -= 360.0;

With this, you are sure that :

  • startLong is between 0.0 and 360.0 (exclusive for the later)
  • nextLong is between startLong and startLong + 360.0