我試圖設置地圖區域(中心和跨度),以便地圖同時顯示所有針腳註釋。iPhone MKMapView:設置地圖區域以顯示地圖上的所有針腳
我無法將長/緯度座標從NSString轉換爲double,resp。與他們進行計算。下面是我使用的代碼:
- (void)updateMemberPins{
//calculate new region to show on map
double center_long = 0.0f;
double center_lat = 0.0f;
double max_long = 0.0f;
double min_long = 0.0f;
double max_lat = 0.0f;
double min_lat = 0.0f;
for (Member *member in members) {
//find min and max values
if ([member.locLat doubleValue] > max_lat) {max_lat = [member.locLat doubleValue];}
if ([member.locLat doubleValue] < min_lat) {min_lat = [member.locLat doubleValue];}
if ([member.locLong doubleValue] > max_long) {max_long = [member.locLong doubleValue];}
if ([member.locLong doubleValue] < min_long) {min_long = [member.locLong doubleValue];}
//sum up long and lang to get average later
center_lat = center_lat + [member.locLat doubleValue];
center_long = center_long + [member.locLong doubleValue];
}
//calculate average long/lat
center_lat = center_lat/[members count];
center_long = center_long/[members count];
NSLog(@"center long: %d, center lat: %d", center_long, center_lat);
NSLog(@"max_long: %d, min_long: %d, max_lat: %d, min_lat: %d", max_long, min_long, max_lat, min_lat);
//create new region and set map
CLLocationCoordinate2D coord = {latitude: center_lat, longitude: center_long};
MKCoordinateSpan span = MKCoordinateSpanMake(abs(max_lat) + abs(min_lat), abs(max_long) + abs(min_long));
MKCoordinateRegion region = {coord, span};
[resultMapView setRegion:region];
//remove all pins from map
[resultMapView removeAnnotations:resultMapView.annotations];
//show member pins
for (id member in members) {
[resultMapView addAnnotation:(Member *) member];
}
}
日誌輸出的結果是:
中心長:-1946827116,中心緯度:1075651472
max_long:-6267216,min_long:1076018553,max_lat:0,min_lat:0
我瘦k問題來自(錯誤地)將NSString的值轉換爲double,但是我無法找到使其工作的方式...位置字符串的格式類似於'43.5686473'。
任何提示? Cheerz
您的min min lat lon的起始值是錯誤的。試試這些:double max_long = -360.0f; double min_long = 360.0f; double max_lat = -360.0f; double min_lat = 360.0f; – igrek 2013-05-14 12:58:44
和跨度計算?爲什麼添加它們?並且abs返回int不是雙倍,所以應該是fabs:MKCoordinateSpan span = MKCoordinateSpanMake(fabs(max_lat-min_lat),fabs(max_long - min_long)); – igrek 2013-05-14 13:05:44
無論如何,+1它爲我節省了一些時間 – igrek 2013-05-14 13:06:01