[英]Fitting annotations on a MKMapView while keeping user position centered
我試圖在我的MKMapView
上容納所有注釋,同時將當前用戶位置保持在地圖中心。
關於如何縮小區域以適應地圖上的注釋,已經有很多參考文獻[1] [2],但是它們會調整當前的中心位置,例如,如果所有注釋都位於我當前用戶位置的東邊,它將進行調整,以便當前用戶位置在地圖左側移動。
如何縮小地圖,使其適合顯示的所有注釋,但保持用戶當前在地圖中心的位置?
參考文獻:
[2] - (void)showAnnotations:(NSArray *)annotations animated:(BOOL)animated NS_AVAILABLE(10_9, 7_0);
我發現此解決方案是最可靠的,@ Anna也建議使用此解決方案,因此它可能是一個好的解決方案。
這是我的方法(作為繼承的MKMapView
的方法實現
- (void)fitAnnotationsKeepingCenter {
CLLocation *centerLocation = [[CLLocation alloc]
initWithLatitude:self.centerCoordinate.latitude
longitude:self.centerCoordinate.longitude];
// starting distance (do not zoom less than this)
CLLocationDistance maxDistance = 350;
for (id <MKAnnotation> vehicleAnnotation in [self annotations]) {
CLLocation *annotationLocation = [[CLLocation alloc] initWithLatitude:vehicleAnnotation.coordinate.latitude longitude:vehicleAnnotation.coordinate.longitude];
maxDistance = MAX(maxDistance, [centerLocation distanceFromLocation:annotationLocation]);
}
MKCoordinateRegion fittedRegion = MKCoordinateRegionMakeWithDistance(centerLocation.coordinate, maxDistance * 2, maxDistance * 2);
fittedRegion = [self regionThatFits:fittedRegion];
fittedRegion.span.latitudeDelta *= 1.2;
fittedRegion.span.longitudeDelta *= 1.2;
[self setRegion:fittedRegion animated:YES];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.