Zoom MKMapView pour ajuster les broches d’annotation?

J’utilise MKMapView et j’ai ajouté plusieurs broches d’annotation à la carte sur une zone de 5 à 10 kilomètres. Lorsque je lance l’application, la carte commence à zoomer pour montrer au monde entier, quelle est la meilleure façon de zoomer sur la carte pour que les broches correspondent à la vue?

EDIT: Ma première pensée serait d’utiliser MKCoordinateRegionMake et de calculer le centre de coordonnées, longitudeDelta et latitudeDelta à partir de mes annotations. Je suis quasiment sûr que cela fonctionnera, mais je voulais juste vérifier que je ne manquais de rien.

Code ajouté, BTW: FGLocation est une classe conforme à MKAnnotation , locationFake est un NSMutableArray de ces objects. Les commentaires sont toujours les bienvenus ….

 - (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  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; } 

Vous avez raison.

Trouvez vos latitudes et longitudes maximales et minimales, appliquez une arithmétique simple et utilisez MKCoordinateRegionMake .

Pour iOS 7 et supérieur, utilisez showAnnotations:animated: MKMapView.h partir de 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); 

C’est celui que j’ai trouvé ici qui a fonctionné pour moi:

(EDIT: J’ai mis à jour la solution en utilisant la suggestion de @ Micah pour augmenter le pointRect de 0,1 afin de garantir que le rect final ne soit pas infiniment petit!)

 MKMapRect zoomRect = MKMapRectNull; for (id  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]; 

Vous pouvez également mettre à jour ceci pour inclure la broche userLocation en remplaçant la première ligne par:

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

Apple a ajouté une nouvelle méthode pour IOS 7 pour simplifier un peu la vie.

 [mapView showAnnotations:yourAnnotationArray animated:YES]; 

Vous pouvez facilement tirer d’un tableau stocké dans la vue cartographique:

 yourAnnotationArray = mapView.annotations; 

et ajustez rapidement la caméra aussi!

 mapView.camera.altitude *= 1.4; 

Cela ne marchera que si l’utilisateur a installé iOS 7+ ou OS X 10.9+. Découvrez l’animation personnalisée ici

J’utilise ce code et fonctionne bien pour moi:

 -(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]; } 

En utilisation rapide

 mapView.showAnnotations(annotationArray, animated: true) 

En objective c

 [mapView showAnnotations:annotationArray animated:YES]; 

La solution de @ jowie fonctionne très bien. Une capture, si une carte ne comporte qu’une seule annotation, vous vous retrouverez avec une carte entièrement zoomée. J’ai ajouté 0.1 à la taille du rectangle pour s’assurer que setVisibleMapRect a quelque chose à zoomer.

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

J’ai converti la réponse par Rafael Moreira. Le crédit lui revient. Pour ceux qui recherchent la version Swift, voici le code:

  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) } 

Si vous recherchez iOS 8 ou une var layoutMargins: UIEdgeInsets { get set } , la méthode la plus simple consiste à définir la var layoutMargins: UIEdgeInsets { get set } de votre vue cartographique avant d’appeler func showAnnotations(annotations: [MKAnnotation], animated: Bool)

Par exemple (Swift 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) } 

Swift 3 Il s’agit d’une manière correcte pour ajuster toutes les annotations sur la carte.

 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) } 

Ajout de cette boucle If dans la boucle for pour exclure le pin de localisation des utilisateurs de cette méthode (requirejs dans mon cas, et peut-être d’autres)

 if (![annotation isKindOfClass:[MKUserLocation class]] ) { //Code Here... } 

Pour iOS 7 et versions ultérieures (en référence à 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); 

remarque de – Abhishek Bedi

Vous appelez simplement:

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

J’ai créé une extension pour afficher toutes les annotations en utilisant un code d’ici et d’ailleurs dans swift. Cela ne montrera pas toutes les annotations si elles ne peuvent pas être affichées même au niveau de zoom maximum.

 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) } } 

En swift

  var zoomRect = MKMapRectNull; for i in 0.. 

Grâce à jowie, j’ai mis à jour mon ancienne catégorie vers une solution plus élégante. Partage complet, presque copier et coller une solution prête

MKMapView + AnnotationsRegion.h

 #import  @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 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 

J’espère que ça aide quelqu’un et merci encore jowie!

  - (void)zoomMapViewToFitAnnotationsWithExtraZoomToAdjust:(double)extraZoom { if ([self.annotations count] == 0) return; int i = 0; MKMapPoint points[[self.annotations count]]; for (id 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]; } 

Comme le souligne Abhishek Bedi dans un commentaire, pour iOS7, la meilleure façon de procéder est la suivante:

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

Pour mon projet personnel (avant iOS7), j’ai simplement ajouté une catégorie sur la classe MKMapView pour encapsuler la fonctionnalité “zone visible” pour une opération très courante: la configurer pour pouvoir voir toutes les annotations actuellement chargées sur l’instance MKMapView ( Cela inclut autant de broches que vous avez pu placer, ainsi que l’emplacement de l’utilisateur. le résultat était le suivant:

Fichier .h

 #import  @interface MKMapView (Extensions) -(void)ij_setVisibleRectToFitAllLoadedAnnotationsAnimated:(BOOL)animated; -(void)ij_setVisibleRectToFitAnnotations:(NSArray *)annotations animated:(BOOL)animated; @end 

fichier .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  protocol in order to fetch the coordinates to compute the visible region of the map. * * @param annotations an array of elements conforming to the  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 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(px, py, 0, 0)); } [mapView setVisibleMapRect:r animated:animated]; } @end 

Comme vous pouvez le voir, j’ai ajouté 2 méthodes jusqu’ici: une pour définir la région visible de la carte sur celle qui correspond à toutes les annotations actuellement chargées sur l’instance MKMapView et une autre méthode pour la définir sur n’importe quel tableau d’objects. Donc, pour définir la région visible de la mapView, le code serait aussi simple que:

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

J’espère que ça aide =)

  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) 

J’ai apporté une petite modification au code de Rafael pour la catégorie 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  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]; } 

Toutes les réponses sur cette page supposent que la carte occupe tout l’écran . J’ai en fait un affichage HUD (c.-à-d. Des boutons dispersés en haut et en bas) qui donnent des informations sur la carte. Les algorithmes de la page affichent donc les broches, mais certaines apparaîtront sous les boutons .

Ma solution fait un zoom avant sur la carte pour afficher les annotations dans un sous-ensemble de l’écran et fonctionne pour différentes tailles d’écran (par exemple, 3,5 “contre 4,0”, etc.):

 // 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. 

Voici ce que j’ai fait dans le code (note: j’utilise NSConstraints avec certaines méthodes d’aide pour faire fonctionner mon code dans différentes tailles d’écran .. alors que le code est assez lisible … ma réponse explique mieux … c’est essentiellement le même workflow: )

 // 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]; 

Voici le code qui obtient la région qui convient:

 - (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; } 

Juste partager mes observations à ce sujet:

Si vous utilisez xCode> 6 avec des tailles “inférées” pour les écrans (voir “mesures simulées” sur l’inspecteur de fichiers) dans le storyboard, appel

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

in viewDidLoad entraînera un niveau de zoom trop élevé sur les iPhones de 4 pouces car la disposition de la carte est toujours de la taille des écrans plus larges du storyboard.

Vous pouvez déplacer votre appel à showAnnotations... pour viewDidAppear . Ensuite, la taille de la carte a déjà été ajustée au petit écran d’un iPhone 4.

Ou alternativement, changez la valeur “infected” dans l’inspecteur de fichiers sous “mésortingques simulées” pour iphone 4 inch.

Sur la base des réponses ci-dessus, vous pouvez utiliser la méthode universelle pour zoomer sur la carte afin de l’adapter à toutes les annotations et superpositions en même temps.

 -(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  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  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; } 

Et alors:

 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]; 

@ “Je ne suis pas sûr que cela soit dû à d’autres facteurs dans mon implémentation, mais je trouve que showAnnotations ne fait pas un zoom / ajustement aussi proche des annotations que l’implémentation manuelle, donc je suis coincé avec manuel. – Ted Avery 17 avril à 0:35 ”

J’ai eu le même problème, mais j’ai essayé de faire deux fois showAnnotations (comme ci-dessous), et pour une raison quelconque, cela a fonctionné.

[mapView showAnnotations: votreAnnotationArray animé: OUI]; [mapView showAnnotations: votreAnnotationArray animé: OUI];

Une méthode compatible avec iOS 7 consiste à utiliser les éléments suivants. Appelez d’abord showAnnotation pour obtenir un rectangle incluant toutes les annotations. Créez ensuite et UIEdgeInset avec un encart supérieur de la hauteur de la broche. Ainsi, vous vous assurez de montrer la broche entière sur la carte.

 [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]; 

Mettez ceci dans votre code en conséquence:

  - (void)mapView:(MKMapView *)mv didAddAnnotationViews:(NSArray *)views { id mp = [annotationView annotation]; MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance([mp coordinate] ,250,250); [mv setRegion:region animated:YES]; }