缩放 MKMapView 以适应注释图钉?

Zooming MKMapView to fit annotation pins?(缩放 MKMapView 以适应注释图钉?)

本文介绍了缩放 MKMapView 以适应注释图钉?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using MKMapView and have added a number of annotation pins to the map about a 5-10 kilometre area. When I run the application my map starts zoomed out to show the whole world, what is the best way to zoom the map so the pins fit the view?

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

My initial thinking would be to use MKCoordinateRegionMake and calculate the coordinate centre, longitudeDelta and latitudeDelta from my annotations. I am pretty sure this will work, but I just wanted to check I was not missing anything obvious.

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

Code added, BTW: FGLocation is an class that conforms to MKAnnotation, locationFake is an NSMutableArray of these objects. Comments are always welcome ....

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

推荐答案

你做对了.

找到你的最大和最小纬度和经度,应用一些简单的算术,然后使用 MKCoordinateRegionMake.

Find your maximum and minimum latitudes and longitudes, apply some simple arithmetic, and use MKCoordinateRegionMake.

对于 iOS 7 及更高版本,使用 showAnnotations:animated:,来自 MKMapView.h:

For iOS 7 and above, use showAnnotations:animated:, from MKMapView.h:

// Position the map such that the provided array of annotations are all visible to the fullest extent possible. 
- (void)showAnnotations:(NSArray *)annotations animated:(BOOL)animated NS_AVAILABLE(10_9, 7_0);

这篇关于缩放 MKMapView 以适应注释图钉?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:缩放 MKMapView 以适应注释图钉?

基础教程推荐