Display MKMapViewAnnotations within a map view's visible rect

后端 未结 7 653
梦毁少年i
梦毁少年i 2021-02-02 02:31

I\'m displaying an MKMapView inside a Path-style parallax table view header. To create the effect, the mapView bounds is larger than the area visible to the user. I need to set

7条回答
  •  悲哀的现实
    2021-02-02 02:59

    Try to get from all your annotation edges value (max and min) for lan and lon.

    Define this value on the beginning:

    static float maxLat = FLT_MIN;
    static float maxLon = FLT_MIN;
    static float minLat = FLT_MAX;
    static float minLon = FLT_MAX;
    

    and then use this function to calculate span and region:

    - (void) zoomAndFit {
        for(int i = 0; i < [self.points count]; i++) {
            PRPlaceModel *place = [self.points objectAtIndex:i];
            CLLocationCoordinate2D location; 
            location.latitude = [place.lat floatValue];
            location.longitude = [place.lon floatValue];
            minLat = MIN(minLat, location.latitude);
            minLon = MIN(minLon, location.longitude);
            maxLat = MAX(maxLat, location.latitude);
            maxLon = MAX(maxLon, location.longitude);
        }
        MKCoordinateRegion region; 
        MKCoordinateSpan span; 
        span.latitudeDelta = 1.2*(maxLat - minLat); 
        span.longitudeDelta = 1.2*(maxLon - minLon);
    
        CLLocationCoordinate2D location; 
        location.latitude = (minLat + maxLat)/2;
        location.longitude = (minLon + maxLon)/2;
    
        region.span=span; 
        region.center=location; 
        [self.mapView setRegion:region animated:TRUE]; 
        [self.mapView regionThatFits:region]; 
    }
    

    And use it in viewDidLoad method:

    -(void)viewDidLoad
    {
        [super viewDidLoad];
        [self zoomAndFit];
    }
    

提交回复
热议问题