我有以下代码来计算MKCoordinateRegion以显示包含两个定义点的地图。问题是当经度超过180度或-180度时,它不起作用。
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];
我有什么想法可以改变这段代码,以确保它可以处理startLong为正,即174和nextLong为负,即-127,反之亦然
答案 0 :(得分:0)
由于startLong
和nextLong
是经度,因此从0°到360°,您可以确保它们都是正数,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;
有了这个,你确定:
startLong
介于0.0和360.0之间(仅限于后者)nextLong
介于startLong
和startLong
+ 360.0