2012-02-29 73 views
1

我有一個算法可以計算包含一組給定座標的地圖的邊界框的大小和位置。雖然它完美,它產生的界限並不總是容納圖釘,我在的地方,往往在於對上邊框的邊緣座標:帶註解的地圖邊界框

enter image description here

...又一次,它產生可接受的結果大部分的時間:

enter image description here

我已經研磨過的過來一段時間,但我一直沒能想辦法改變我的算法,以確保推進銷總是在邊界框內。我的算法列在下面,任何建議將不勝感激。 :)

MKMapPoint *points = malloc([coordinates count] * sizeof(MKMapPoint));  
MKMapPoint upperRightCorner; 
MKMapPoint lowerLeftCorner; 

for(int i = 0; i < [coordinates count]; i++) 
{ 
    CLLocation *location = [coordinates objectAtIndex:i]; 
    CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(herp.coordinate.latitude, herp.coordinate.longitude); 

    MKMapPoint point = MKMapPointForCoordinate(coordinate); 
    points[i] = point; 

    if (i == 0) { 
     upperRightCorner = point; 
     lowerLeftCorner = point; 
    } 
    else { 
     if (point.x > upperRightCorner.x) upperRightCorner.x = point.x; 
     if (point.y > upperRightCorner.y) upperRightCorner.y = point.y; 
     if (point.x < lowerLeftCorner.x) lowerLeftCorner.x = point.x; 
     if (point.y < lowerLeftCorner.y) lowerLeftCorner.y = point.y; 
    }  
} 

MKMapRect boundingBox = MKMapRectMake(lowerLeftCorner.x, lowerLeftCorner.y, 
           upperRightCorner.x - lowerLeftCorner.x, 
           upperRightCorner.y - lowerLeftCorner.y); 
+0

...在頂部加入填充一下呢?這是最簡單的方法:) – Ryan 2012-02-29 03:13:59

+0

不是你的問題的答案,但這可以通過使用LatLngBounds的擴展方法來簡化 – 2012-02-29 08:38:19

回答

3

我想這可能是晚了,但這裏是我的作品的解決方案,非常類似於你,我結束了在最後增加填充。

- (MKCoordinateRegion)boundingBoxForAnnotations:(NSArray *)annotations { 

CLLocationCoordinate2D topLeftCoord; 
topLeftCoord.latitude = -90; 
topLeftCoord.longitude = 180; 

CLLocationCoordinate2D bottomRightCoord; 
bottomRightCoord.latitude = 90; 
bottomRightCoord.longitude = -180; 

for (id<MKAnnotation> annotation in annotations) { 

    topLeftCoord.longitude = fmin(topLeftCoord.longitude, annotation.coordinate.longitude); 
    topLeftCoord.latitude = fmax(topLeftCoord.latitude, annotation.coordinate.latitude); 
    bottomRightCoord.longitude = fmax(bottomRightCoord.longitude, annotation.coordinate.longitude); 
    bottomRightCoord.latitude = fmin(bottomRightCoord.latitude, annotation.coordinate.latitude); 
} 

MKCoordinateRegion region; 
region.center.latitude = topLeftCoord.latitude - (topLeftCoord.latitude - bottomRightCoord.latitude) * 0.5; 
region.center.longitude = topLeftCoord.longitude + (bottomRightCoord.longitude - topLeftCoord.longitude) * 0.5; 
region.span.latitudeDelta = fabs(topLeftCoord.latitude - bottomRightCoord.latitude) * 1.1; 

region.span.longitudeDelta = fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.1; 

return region; 

}