Zoom to fit region for all annotations - ending up zooming in between annotations

后端 未结 2 765
盖世英雄少女心
盖世英雄少女心 2021-01-03 05:54

I have a problem with fitting all my annotations to the screen... sometimes it shows all annotations, but some other times the app is zooming in between the two annotations

2条回答
  •  别那么骄傲
    2021-01-03 06:29

    Use the following code

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

提交回复
热议问题