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

拥有回忆 提交于 2019-11-30 15:30:32
Satya

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

Instead of:

region.span.latitudeDelta = meter / 111319.5;
 region.span.longitudeDelta = 0.0;
 region.center.latitude = (SouthWest.latitude + NorthEast.latitude) / 2.0;
 region.center.longitude = (SouthWest.longitude + NorthEast.longitude) / 2.0;

Try adding:

region.span.latitudeDelta = fabs(NorthEast.latitude - SouthWest.latitude) * 1.2; 
region.span.longitudeDelta = fabs(SouthWest.longitude - NorthEast.longitude) * 1.2; 
region.center.latitude = NorthEast.latitude - (NorthEast.latitude - SouthWest.latitude) * 0.5;
region.center.longitude = NorthEast.longitude + (SouthWest.longitude - NorthEast.longitude) * 0.5;

And removing:

CLLocationDistance meter = [locSouthWest distanceFromLocation:locNorthEast];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!