What's the best way to zoom out and fit all annotations in MapKit

前端 未结 4 1562
醉梦人生
醉梦人生 2020-12-12 17:49

Quick background of what I have going on. UIMapView loads and shows a single annotation (Never more than one). On the menu bar, there is a Locate Me button, on tap the use

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-12 18:03

    -(void)zoomToFitMapAnnotations:(MKMapView*)mapView
    {
        if([mapView.annotations count] == 0)
            return;
    
        CLLocationCoordinate2D topLeftCoord;
        topLeftCoord.latitude = -90;
        topLeftCoord.longitude = 180;
    
        CLLocationCoordinate2D bottomRightCoord;
        bottomRightCoord.latitude = 90;
        bottomRightCoord.longitude = -180;
    
        for(MapAnnotation* 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 = [mapView regionThatFits:region];
        [mapView setRegion:region animated:YES];
    }
    

    Taken from: http://codisllc.com/blog/zoom-mkmapview-to-fit-annotations/

    (Use it all the time.)

提交回复
热议问题