iOS开发学习之MapKit - 获得在MapView(地图)中显示多个标记的区域(MKCoordinateRegion)

-(MKCoordinateRegion)regionForAnnotations:(NSArray *)annotations  //可原封不动的复制运用

{

    MKCoordinateRegion region;

    

    if([annotations count] == 0)

    {

        region = MKCoordinateRegionMakeWithDistance(self.mapView.userLocation.coordinate, 1000, 1000);

    }

    else if([annotations count] == 1)

    {

        id <MKAnnotation> annotation = [annotations lastObject];

        region = MKCoordinateRegionMakeWithDistance(annotation.coordinate, 1000, 1000);

    }

    else

    {

        CLLocationCoordinate2D topLeftCoord;

        topLeftCoord.latitude = -90;

        topLeftCoord.longitude = 180;

        

        CLLocationCoordinate2D bottomRightCoord;

        bottomRightCoord.latitude = 90;

        bottomRightCoord.longitude = -180;

        

        for(id <MKAnnotation> annotation in annotations)

        {

            topLeftCoord.latitude = fmax(topLeftCoord.latitude, annotation.coordinate.latitude);

            topLeftCoord.longitude = fmin(topLeftCoord.longitude, annotation.coordinate.longitude);

            bottomRightCoord.latitude = fmin(bottomRightCoord.latitude, annotation.coordinate.latitude);

            bottomRightCoord.longitude = fmax(bottomRightCoord.longitude, annotation.coordinate.longitude);

        }

        

        const double extraSpace = 1.1;

        

        region.center.latitude = topLeftCoord.latitude - (topLeftCoord.latitude - bottomRightCoord.latitude) / 2.0;

        region.center.longitude = topLeftCoord.longitude - (topLeftCoord.longitude - bottomRightCoord.longitude) / 2.0;

        region.span.latitudeDelta = fabs(topLeftCoord.latitude - bottomRightCoord.latitude) * extraSpace;

        region.span.longitudeDelta = fabs(topLeftCoord.longitude - bottomRightCoord.longitude) * extraSpace;

    }

    return [self.mapView regionThatFits:region];

}

 

使用说明:

-(IBAction)showLocations

{

    MKCoordinateRegion region = [self regionForAnnotations:_locations];  

    //调用以上方法,获得一个MKCoordinateRegion区域,该区域包含_locations里的多个标记

    

    [self.mapView setRegion:region animated:YES];

}

 

注意:_locations里的对象必须实现协议MKAnnotation,并实现以下三个方法:

-(CLLocationCoordinate2D)coordinate

{

    return CLLocationCoordinate2DMake([self.latitude doubleValue], [self.longitude doubleValue]);

}

 

-(NSString *)title

{

    if([self.locationDescription length] > 0)

    {

        return self.locationDescription;

    }

    else

    {

        return @"(No Description)";

    }

}

 

-(NSString *)subtitle

{

    return self.category;

}

posted @ 2016-06-08 22:36  XuDeHong  阅读(302)  评论(0编辑  收藏  举报