2011-01-13 89 views
176

我正在使用MKMapView,並在地圖上添加了大量5-10公里區域的註釋引腳。當我運行應用程序時,我的地圖開始縮小以顯示整個世界,縮放地圖的最佳方式是什麼,以便引腳適合視圖?縮放MKMapView以適應註釋引腳?

編輯: 我最初的想法是使用MKCoordinateRegionMake和計算從我的註釋座標中心,longitudeDelta和latitudeDelta。我很確定這會起作用,但我只是想檢查我沒有錯過任何明顯的事情。

已添加代碼,BTW:FGLocation是一個符合MKAnnotation的類,locationFake是這些對象的NSMutableArray。總是歡迎評論....

- (MKCoordinateRegion)regionFromLocations { 
    CLLocationCoordinate2D upper = [[locationFake objectAtIndex:0] coordinate]; 
    CLLocationCoordinate2D lower = [[locationFake objectAtIndex:0] coordinate]; 

    // FIND LIMITS 
    for(FGLocation *eachLocation in locationFake) { 
     if([eachLocation coordinate].latitude > upper.latitude) upper.latitude = [eachLocation coordinate].latitude; 
     if([eachLocation coordinate].latitude < lower.latitude) lower.latitude = [eachLocation coordinate].latitude; 
     if([eachLocation coordinate].longitude > upper.longitude) upper.longitude = [eachLocation coordinate].longitude; 
     if([eachLocation coordinate].longitude < lower.longitude) lower.longitude = [eachLocation coordinate].longitude; 
    } 

    // FIND REGION 
    MKCoordinateSpan locationSpan; 
    locationSpan.latitudeDelta = upper.latitude - lower.latitude; 
    locationSpan.longitudeDelta = upper.longitude - lower.longitude; 
    CLLocationCoordinate2D locationCenter; 
    locationCenter.latitude = (upper.latitude + lower.latitude)/2; 
    locationCenter.longitude = (upper.longitude + lower.longitude)/2; 

    MKCoordinateRegion region = MKCoordinateRegionMake(locationCenter, locationSpan); 
    return region; 
} 
+7

的iOS 7注:新[showAnnotations:動畫:](https://developer.apple.com/library/ios/documentation/MapKit/Reference/MKMapView_Class/MKMapView/MKMapView.html#//apple_ref/doc/uid/TP40008205-CH3-SW83)方法可幫助您避免此手動區域計算。 – Anna 2013-10-16 01:12:24

回答

98

你說得沒錯。

找到您的最大和最小的緯度和經度,應用一些簡單的算術,並使用MKCoordinateRegionMake

對於iOS 7及以上的,使用showAnnotations:animated:,從MKMapView.h

// Position the map such that the provided array of annotations are all visible to the fullest extent possible. 
- (void)showAnnotations:(NSArray *)annotations animated:(BOOL)animated NS_AVAILABLE(10_9, 7_0); 
+151

**對於iOS 7和上述(參照MKMapView.h):** `//位置地圖,使得提供的註釋的陣列都在最大程度上可見possible.` ' - (無效)showAnnotations:(NSArray的*)註釋動畫:(BOOL)動畫NS_AVAILABLE(10_9,7_0);` – 2014-01-30 20:01:58

+1

這種運作良好,但偶爾,當我放大(在地圖),然後嘗試居中(使用一個按鈕,調用該方法)它似乎沒有工作。 – RPM 2015-07-10 19:20:03

+4

需要注意的是`showAnnotations`還增加了註釋地圖,即使該位置的註釋已經存在很重要。 – 2016-02-29 22:26:39

326

這是我發現here爲我工作的一個:

(編輯:我已經更新使用@米迦的解決方案建議增加pointRect 0.1以確保矩形不會最終變得無限小!)

MKMapRect zoomRect = MKMapRectNull; 
for (id <MKAnnotation> annotation in mapView.annotations) 
{ 
    MKMapPoint annotationPoint = MKMapPointForCoordinate(annotation.coordinate); 
    MKMapRect pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0.1, 0.1); 
    zoomRect = MKMapRectUnion(zoomRect, pointRect); 
} 
[mapView setVisibleMapRect:zoomRect animated:YES]; 

 

你也可以更新此通過更換第一行,以包括用戶位置針:

MKMapPoint annotationPoint = MKMapPointForCoordinate(mapView.userLocation.coordinate); 
MKMapRect zoomRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0.1, 0.1); 
13

@ jowie的解決方案的偉大工程。一個問題是,如果一張地圖只有一個註釋,那麼你最終會得到一張完全縮小的地圖。我在rect make size中加了0.1,以確保setVisibleMapRect有一些可以放大的東西。

MKMapRect pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0.1, 0.1); 
7

新增內的for循環這個如果循環排除此方法的用戶定位銷(需要在我的情況,或者其他人)

if (![annotation isKindOfClass:[MKUserLocation class]]) { 

//Code Here... 

} 
0

在相應的代碼將這個:

- (void)mapView:(MKMapView *)mv didAddAnnotationViews:(NSArray *)views 
    { 
    id<MKAnnotation> mp = [annotationView annotation]; 
     MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance([mp coordinate] ,250,250); 

     [mv setRegion:region animated:YES]; 

} 
42

我用這個這個代碼,併爲我工作得很好:

-(void)zoomToFitMapAnnotations:(MKMapView*)aMapView 
{ 
    if([aMapView.annotations count] == 0) 
     return; 

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

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

    for(MapViewAnnotation *annotation in mapView.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; // Add a little extra space on the sides 
    region.span.longitudeDelta = fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.1; // Add a little extra space on the sides 

    region = [aMapView regionThatFits:region]; 
    [mapView setRegion:region animated:YES]; 
} 
2

我已經做了一些修改Rafael的 MKMapView類的代碼。

- (void)zoomToFitMapAnnotations { 
    if ([self.annotations count] == 0) 
     return; 

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

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

    for (id <MKAnnotation> annotation in self.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; // Add a little extra space on the sides 
    region.span.longitudeDelta = fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.1; // Add a little extra space on the sides 

    [self setRegion:[self regionThatFits:region] animated:YES]; 
} 
2

所有此頁面上的答案假設地圖佔據全屏。我實際上有一個HUD顯示屏(即頂部和底部分散的按鈕),可以在地圖上顯示信息。因此,頁面上的算法將顯示引腳,但其中一些會顯示,在下HUD顯示按鈕。

我的解決方案將放大到顯示在子屏幕註釋地圖,適用於不同的屏幕尺寸(即3.5" 與4.0" 等):

// create a UIView placeholder and throw it on top of the original mapview 
// position the UIView to fit the maximum area not hidden by the HUD display buttons 
// add an *other* mapview in that uiview, 
// get the MKCoordinateRegion that fits the pins from that fake mapview 
// kill the fake mapview and set the region of the original map 
// to that MKCoordinateRegion. 

這裏是什麼我在代碼(注:我使用NSConstraints與一些幫手方法,使我的代碼工作在不同的屏幕尺寸..雖然代碼是非常可讀的..我的回答here解釋它更好..它基本上是相同的工作流程:)

// position smallerMap to fit available space 
// don't store this map, it will slow down things if we keep it hidden or even in memory 
[@[_smallerMapPlaceholder] mapObjectsApplyingBlock:^(UIView *view) { 
    [view removeFromSuperview]; 
    [view setTranslatesAutoresizingMaskIntoConstraints:NO]; 
    [view setHidden:NO]; 
    [self.view addSubview:view]; 
}]; 

NSDictionary *buttonBindingDict = @{ @"mapPlaceholder": _smallerMapPlaceholder}; 

NSArray *constraints = [@[@"V:|-225-[mapPlaceholder(>=50)]-176-|", 
          @"|-40-[mapPlaceholder(<=240)]-40-|" 
          ] mapObjectsUsingBlock:^id(NSString *formatString, NSUInteger idx){ 
           return [NSLayoutConstraint constraintsWithVisualFormat:formatString options:0 metrics:nil views:buttonBindingDict]; 
          }]; 

[self.view addConstraints:[constraints flattenArray]]; 
[self.view layoutIfNeeded]; 

MKMapView *smallerMap = [[MKMapView alloc] initWithFrame:self.smallerMapPlaceholder.frame]; 
[_smallerMapPlaceholder addSubview:smallerMap]; 

MKCoordinateRegion regionThatFits = [smallerMap getRegionThatFits:self.mapView.annotations]; 
[smallerMap removeFromSuperview]; 
smallerMap = nil; 
[_smallerMapPlaceholder setHidden:YES]; 

[self.mapView setRegion:regionThatFits animated:YES]; 

這裏是獲取適合區域代碼:

- (MKCoordinateRegion)getRegionThatFits:(NSArray *)routes { 
    MKCoordinateRegion region; 
    CLLocationDegrees maxLat = -90.0; 
    CLLocationDegrees maxLon = -180.0; 
    CLLocationDegrees minLat = 90.0; 
    CLLocationDegrees minLon = 180.0; 
    for(int idx = 0; idx < routes.count; idx++) 
    { 
     CLLocation* currentLocation = [routes objectAtIndex:idx]; 
     if(currentLocation.coordinate.latitude > maxLat) 
      maxLat = currentLocation.coordinate.latitude; 
     if(currentLocation.coordinate.latitude < minLat) 
      minLat = currentLocation.coordinate.latitude; 
     if(currentLocation.coordinate.longitude > maxLon) 
      maxLon = currentLocation.coordinate.longitude; 
     if(currentLocation.coordinate.longitude < minLon) 
      minLon = currentLocation.coordinate.longitude; 
    } 
    region.center.latitude  = (maxLat + minLat)/2.0; 
    region.center.longitude = (maxLon + minLon)/2.0; 
    region.span.latitudeDelta = 0.01; 
    region.span.longitudeDelta = 0.01; 

    region.span.latitudeDelta = ((maxLat - minLat)<0.0)?100.0:(maxLat - minLat); 
    region.span.longitudeDelta = ((maxLon - minLon)<0.0)?100.0:(maxLon - minLon); 

    MKCoordinateRegion regionThatFits = [self regionThatFits:region]; 
    return regionThatFits; 
} 
3

感謝jowie我已經更新了我的老品類更優雅的解決方案。分享完整的,幾乎複製粘貼&現成的解決方案

的MKMapView + AnnotationsRegion.h

#import <MapKit/MapKit.h> 

@interface MKMapView (AnnotationsRegion) 

-(void)updateRegionForCurrentAnnotationsAnimated:(BOOL)animated; 
-(void)updateRegionForCurrentAnnotationsAnimated:(BOOL)animated edgePadding:(UIEdgeInsets)edgePadding; 

-(void)updateRegionForAnnotations:(NSArray *)annotations animated:(BOOL)animated; 
-(void)updateRegionForAnnotations:(NSArray *)annotations animated:(BOOL)animated edgePadding:(UIEdgeInsets)edgePadding; 

@end 

的MKMapView + AnnotationsRegion.m

#import "MKMapView+AnnotationsRegion.h" 

@implementation MKMapView (AnnotationsRegion) 

-(void)updateRegionForCurrentAnnotationsAnimated:(BOOL)animated{ 
    [self updateRegionForCurrentAnnotationsAnimated:animated edgePadding:UIEdgeInsetsZero]; 
} 
-(void)updateRegionForCurrentAnnotationsAnimated:(BOOL)animated edgePadding:(UIEdgeInsets)edgePadding{ 
    [self updateRegionForAnnotations:self.annotations animated:animated edgePadding:edgePadding]; 
} 

-(void)updateRegionForAnnotations:(NSArray *)annotations animated:(BOOL)animated{ 
    [self updateRegionForAnnotations:annotations animated:animated edgePadding:UIEdgeInsetsZero]; 
} 
-(void)updateRegionForAnnotations:(NSArray *)annotations animated:(BOOL)animated edgePadding:(UIEdgeInsets)edgePadding{ 
    MKMapRect zoomRect = MKMapRectNull; 
    for(id<MKAnnotation> annotation in annotations){ 
     MKMapPoint annotationPoint = MKMapPointForCoordinate(annotation.coordinate); 
     MKMapRect pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0.1, 0.1); 
     zoomRect = MKMapRectUnion(zoomRect, pointRect); 
    } 
    [self setVisibleMapRect:zoomRect edgePadding:edgePadding animated:animated]; 
} 

@end 

希望它可以幫助別人,並再次感謝jowie!

115

蘋果已經增加了IOS 7的新方法來簡化生活。

[mapView showAnnotations:yourAnnotationArray animated:YES]; 

您可以輕鬆地從存儲在地圖視圖中的數組拉:

yourAnnotationArray = mapView.annotations; 

並且迅速地調整攝像頭呢!

mapView.camera.altitude *= 1.4; 

這是行不通的,除非用戶的iOS 7+或安裝OS X 10.9+。檢查自定義動畫here

3
- (void)zoomMapViewToFitAnnotationsWithExtraZoomToAdjust:(double)extraZoom 
{ 

    if ([self.annotations count] == 0) return; 

    int i = 0; 
    MKMapPoint points[[self.annotations count]]; 

    for (id<MKAnnotation> annotation in [self annotations]) 
    { 
     points[i++] = MKMapPointForCoordinate(annotation.coordinate); 
    } 

    MKPolygon *poly = [MKPolygon polygonWithPoints:points count:i]; 

MKCoordinateRegion r = MKCoordinateRegionForMapRect([poly boundingMapRect]); 
r.span.latitudeDelta += extraZoom; 
r.span.longitudeDelta += extraZoom; 

[self setRegion: r animated:YES]; 

} 
0

@「我不知道這是因爲我在執行一些其他因素的影響,但我發現showAnnotations不做註釋接近變焦/適合作爲 - 泰德艾利4月17日0:35「

我有同樣的問題,但後來我試圖做showAnnotations兩次(如下圖),併爲一些原因,它的工作。

[mapView showAnnotations:yourAnnotationArray animated:YES]; [mapView showAnnotations:yourAnnotationArray animated:YES];

2

由於阿布舍克貝迪在評論中指出,對於iOS7轉發做到這一點,最好的辦法是:

//from API docs: 
//- (void)showAnnotations:(NSArray *)annotations animated:(BOOL)animated NS_AVAILABLE(10_9, 7_0); 
[self.mapView showAnnotations:self.mapView.annotations animated:YES]; 

對於我的個人項目(之前iOS7)我只是增加了一個類別上的MKMapView類爲一個非常常見的操作封裝「可見區域」功能:將其設置爲能夠查看MKMapView實例上的所有當前加載的註釋(包括儘可能多的引腳以及用戶的位置)。結果是這樣的:

.h文件中

#import <MapKit/MapKit.h> 

@interface MKMapView (Extensions) 

-(void)ij_setVisibleRectToFitAllLoadedAnnotationsAnimated:(BOOL)animated; 
-(void)ij_setVisibleRectToFitAnnotations:(NSArray *)annotations animated:(BOOL)animated; 


@end 

.m文件

#import "MKMapView+Extensions.h" 

@implementation MKMapView (Extensions) 

/** 
* Changes the currently visible portion of the map to a region that best fits all the currently loadded annotations on the map, and it optionally animates the change. 
* 
* @param animated is the change should be perfomed with an animation. 
*/ 
-(void)ij_setVisibleRectToFitAllLoadedAnnotationsAnimated:(BOOL)animated 
{ 
    MKMapView * mapView = self; 

    NSArray * annotations = mapView.annotations; 

    [self ij_setVisibleRectToFitAnnotations:annotations animated:animated]; 

} 


/** 
* Changes the currently visible portion of the map to a region that best fits the provided annotations array, and it optionally animates the change. 
    All elements from the array must conform to the <MKAnnotation> protocol in order to fetch the coordinates to compute the visible region of the map. 
* 
* @param annotations an array of elements conforming to the <MKAnnotation> protocol, holding the locations for which the visible portion of the map will be set. 
* @param animated wether or not the change should be perfomed with an animation. 
*/ 
-(void)ij_setVisibleRectToFitAnnotations:(NSArray *)annotations animated:(BOOL)animated 
{ 
    MKMapView * mapView = self; 

    MKMapRect r = MKMapRectNull; 
    for (id<MKAnnotation> a in annotations) { 
     ZAssert([a conformsToProtocol:@protocol(MKAnnotation)], @"ERROR: All elements of the array MUST conform to the MKAnnotation protocol. Element (%@) did not fulfill this requirement", a); 
     MKMapPoint p = MKMapPointForCoordinate(a.coordinate); 
     //MKMapRectUnion performs the union between 2 rects, returning a bigger rect containing both (or just one if the other is null). here we do it for rects without a size (points) 
     r = MKMapRectUnion(r, MKMapRectMake(p.x, p.y, 0, 0)); 
    } 

    [mapView setVisibleMapRect:r animated:animated]; 

} 

@end 

正如你所看到的,我已經添加2種方法至今:一個用於設置的可見區域映射到適合MKMapView實例上所有當前加載的批註的映射,以及將其設置爲任何對象數組的另一種方法。 所以設置的MapView的可視區域,則代碼將簡單:

//the mapView instance 
    [self.mapView ij_setVisibleRectToFitAllLoadedAnnotationsAnimated:animated]; 

我希望它有助於=)

7

對於iOS 7及以上(參照MKMapView.h):

// Position the map such that the provided array of annotations are all visible to the fullest extent possible.   

- (void)showAnnotations:(NSArray *)annotations animated:(BOOL)animated NS_AVAILABLE(10_9, 7_0); 

句話從 - 阿布舍克貝迪

您只要致電:

[yourMapView showAnnotations:@[yourAnnotation] animated:YES]; 
1

公正地分享這個我的意見:

如果您正在使用的Xcode> 6的屏幕「推斷」大小(見文件檢查器「模擬指標」)的故事板,調用

- (void)showAnnotations:(NSArray *)annotations animated:(BOOL)animated

in viewDidLoad將導致4英寸iPhone上的放大級別過大,因爲地圖的佈局仍處於故事板中較寬屏幕的大小。

您可以將您的電話轉到showAnnotations...viewDidAppear。然後,地圖的大小已經調整到iPhone 4的較小屏幕。

或者將文件檢查器中的「模擬指標」下的「推測」值更改爲iphone 4英寸。

11

我已經由Rafael Moreira轉換了答案。信用歸功於他。 對於那些尋找雨燕的版本,這裏是代碼:

func zoomToFitMapAnnotations(aMapView: MKMapView) { 
    guard aMapView.annotations.count > 0 else { 
     return 
    } 
    var topLeftCoord: CLLocationCoordinate2D = CLLocationCoordinate2D() 
    topLeftCoord.latitude = -90 
    topLeftCoord.longitude = 180 
    var bottomRightCoord: CLLocationCoordinate2D = CLLocationCoordinate2D() 
    bottomRightCoord.latitude = 90 
    bottomRightCoord.longitude = -180 
    for annotation: MKAnnotation in myMap.annotations as! [MKAnnotation]{ 
     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) 
    } 

    var region: MKCoordinateRegion = MKCoordinateRegion() 
    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.4 
    region.span.longitudeDelta = fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.4 
    region = aMapView.regionThatFits(region) 
    myMap.setRegion(region, animated: true) 
} 
9

如果您正在尋找的iOS 8.0及以上,做最簡單的方法是設置你的地圖視圖的var layoutMargins: UIEdgeInsets { get set }調用func showAnnotations(annotations: [MKAnnotation], animated: Bool)

例如(雨燕2.1)前:

@IBOutlet weak var map: MKMapView! { 
    didSet { 
     map.delegate = self 
     map.mapType = .Standard 
     map.pitchEnabled = false 
     map.rotateEnabled = false 
     map.scrollEnabled = true 
     map.zoomEnabled = true 
    } 
} 

// call 'updateView()' when viewWillAppear or whenever you set the map annotations 
func updateView() { 
    map.layoutMargins = UIEdgeInsets(top: 25, left: 25, bottom: 25, right: 25) 
    map.showAnnotations(map.annotations, animated: true) 
} 
0

的的iOS 7兼容的方法是使用下面的。爲了第一次調用showAnnotation獲得包括所有註釋的矩形。之後創建並帶有插針高度頂部插入的UIEdgeInset。因此你確保在地圖上顯示整個針腳。

[self.mapView showAnnotations:self.mapView.annotations animated:YES]; 
MKMapRect rect = [self.mapView visibleMapRect]; 
UIEdgeInsets insets = UIEdgeInsetsMake(pinHeight, 0, 0, 0); 
[self.mapView setVisibleMapRect:rect edgePadding:insets animated:YES]; 
1

根據上面的答案,您可以使用通用方法縮放地圖以同時適合所有註釋和疊加。

-(MKMapRect)getZoomingRectOnMap:(MKMapView*)map toFitAllOverlays:(BOOL)overlays andAnnotations:(BOOL)annotations includeUserLocation:(BOOL)userLocation { 
    if (!map) { 
     return MKMapRectNull; 
    } 

    NSMutableArray* overlaysAndAnnotationsCoordinateArray = [[NSMutableArray alloc]init];   
    if (overlays) { 
     for (id <MKOverlay> overlay in map.overlays) { 
      MKMapPoint overlayPoint = MKMapPointForCoordinate(overlay.coordinate); 
      NSArray* coordinate = @[[NSNumber numberWithDouble:overlayPoint.x], [NSNumber numberWithDouble:overlayPoint.y]]; 
      [overlaysAndAnnotationsCoordinateArray addObject:coordinate]; 
     } 
    } 

    if (annotations) { 
     for (id <MKAnnotation> annotation in map.annotations) { 
      MKMapPoint annotationPoint = MKMapPointForCoordinate(annotation.coordinate); 
      NSArray* coordinate = @[[NSNumber numberWithDouble:annotationPoint.x], [NSNumber numberWithDouble:annotationPoint.y]]; 
      [overlaysAndAnnotationsCoordinateArray addObject:coordinate]; 
     } 
    } 

    MKMapRect zoomRect = MKMapRectNull; 
    if (userLocation) { 
     MKMapPoint annotationPoint = MKMapPointForCoordinate(map.userLocation.coordinate); 
     zoomRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0.1, 0.1); 
    } 

    for (NSArray* coordinate in overlaysAndAnnotationsCoordinateArray) { 
     MKMapRect pointRect = MKMapRectMake([coordinate[0] doubleValue], [coordinate[1] doubleValue], 0.1, 0.1); 
     zoomRect = MKMapRectUnion(zoomRect, pointRect); 
    } 

    return zoomRect; 
} 

然後:

MKMapRect mapRect = [self getZoomingRectOnMap:mapView toFitAllOverlays:YES andAnnotations:YES includeUserLocation:NO]; 
[mapView setVisibleMapRect:mapRect edgePadding:UIEdgeInsetsMake(10.0, 10.0, 10.0, 10.0) animated:YES]; 
13

在斯威夫特使用

mapView.showAnnotations(annotationArray, animated: true) 

目標C

[mapView showAnnotations:annotationArray animated:YES]; 
3
var zoomRect: MKMapRect = MKMapRectNull 
    for annotation in mapView.annotations { 
     let annotationPoint = MKMapPointForCoordinate(annotation.coordinate) 
     let pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0.1, 0.1) 
     zoomRect = MKMapRectUnion(zoomRect, pointRect) 
    } 
    mapView.setVisibleMapRect(zoomRect, animated: true) 
4

在斯威夫特

var zoomRect = MKMapRectNull; 

    for i in 0..<self.map.annotations.count { 

     let annotation: MKAnnotation = self.map.annotations[i] 

     let annotationPoint = MKMapPointForCoordinate(annotation.coordinate); 
     let pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0.1, 0.1); 
     zoomRect = MKMapRectUnion(zoomRect, pointRect); 
    } 

    self.map.setVisibleMapRect(zoomRect, animated: true) 
6

我從這裏迅速創建一個擴展來顯示所有的註釋使用一些代碼,並在那裏。如果即使在最大縮放級別下也無法顯示,則不會顯示所有註釋。

import MapKit 

extension MKMapView { 
    func fitAllAnnotations() { 
     var zoomRect = MKMapRectNull; 
     for annotation in annotations { 
      let annotationPoint = MKMapPointForCoordinate(annotation.coordinate) 
      let pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0.1, 0.1); 
      zoomRect = MKMapRectUnion(zoomRect, pointRect); 
     } 
     setVisibleMapRect(zoomRect, edgePadding: UIEdgeInsetsMake(20, 20, 20, 20), animated: true) 
    } 
} 
7

swift 3這是適合地圖中所有註釋的正確方法。

func zoomMapaFitAnnotations() { 

     var zoomRect = MKMapRectNull 
     for annotation in mapview.annotations { 

      let annotationPoint = MKMapPointForCoordinate(annotation.coordinate) 

      let pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0, 0) 

      if (MKMapRectIsNull(zoomRect)) { 
       zoomRect = pointRect 
      } else { 
       zoomRect = MKMapRectUnion(zoomRect, pointRect) 
      } 
     } 
     self.mapview.setVisibleMapRect(zoomRect, edgePadding: UIEdgeInsetsMake(50, 50, 50, 50), animated: true) 

    }