ios - 缩放 MKMapView 以适应注释图钉?

我正在使用 MKMapView 并在 map 上添加了一些注释图钉,大约 5-10 公里的区域。当我运行应用程序时,我的 map 开始缩小以显示整个世界,缩放 map 以使图钉适合 View 的最佳方法是什么?

编辑: 我最初的想法是使用 MKCoordinateRegionMake 并从我的注释中计算坐标中心、longitudeDelta 和 latitudeDelta。我很确定这会起作用,但我只是想检查一下我没有遗漏任何明显的东西。

添加代码,顺便说一句:FGLocation 是一个符合 MKAnnotation 的类,locationFake 是这些对象的 NSMutableArray。随时欢迎评论....

- (MKCoordinateRegion)regionFromLocations {
    CLLocationCoordinate2D upper = [[locationFake objectAtIndex:0] coordinate];
    CLLocationCoordinate2D lower = [[locationFake objectAtIndex:0] coordinate];

    // FIND LIMITS
    for(FGLocation *eachLocation in locationFake) {
        if([eachLocation coordinate].latitude > upper.latitude) upper.latitude = [eachLocation coordinate].latitude;
        if([eachLocation coordinate].latitude < lower.latitude) lower.latitude = [eachLocation coordinate].latitude;
        if([eachLocation coordinate].longitude > upper.longitude) upper.longitude = [eachLocation coordinate].longitude;
        if([eachLocation coordinate].longitude < lower.longitude) lower.longitude = [eachLocation coordinate].longitude;
    }

    // FIND REGION
    MKCoordinateSpan locationSpan;
    locationSpan.latitudeDelta = upper.latitude - lower.latitude;
    locationSpan.longitudeDelta = upper.longitude - lower.longitude;
    CLLocationCoordinate2D locationCenter;
    locationCenter.latitude = (upper.latitude + lower.latitude) / 2;
    locationCenter.longitude = (upper.longitude + lower.longitude) / 2;

    MKCoordinateRegion region = MKCoordinateRegionMake(locationCenter, locationSpan);
    return region;
}

最佳答案

这是我找到的 here这对我有用:

(编辑:我已经使用@Micah 的建议更新了解决方案,将 pointRect 增加了 0.1,以确保 rect 最终不会变得无限小!)

MKMapRect zoomRect = MKMapRectNull;
for (id <MKAnnotation> annotation in mapView.annotations)
{
    MKMapPoint annotationPoint = MKMapPointForCoordinate(annotation.coordinate);
    MKMapRect pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0.1, 0.1);
    zoomRect = MKMapRectUnion(zoomRect, pointRect);
}
[mapView setVisibleMapRect:zoomRect animated:YES];

 

您还可以通过将第一行替换为以下内容来更新它以包含 userLocation 引脚:

MKMapPoint annotationPoint = MKMapPointForCoordinate(mapView.userLocation.coordinate);
MKMapRect zoomRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0.1, 0.1);

https://stackoverflow.com/questions/4680649/

相关文章:

c - Objective-C : BOOL vs bool

objective-c - respondsToSelector 的 Swift 等价物是什么?

objective-c - Xcode 5 中提供了哪些新的文档命令?

ios - 使用 iOS 将文本复制到剪贴板

objective-c - 在 Objective-C 中,Java 的 "instanceof"关

ios - UITableViewCell 显示白色背景,在 iOS7 上无法修改

objective-c - Xcode 4.4 发行说明中提到的 "Objective-C Lite

objective-c - 为什么 ARC 仍然需要 @autoreleasepool?

objective-c - 洗牌 NSMutableArray 的最佳方法是什么?

ios - 如何对字符串进行 URL 编码