将 MKMapView 缩放到 MKAnnotationView 的框架
Posted
技术标签:
【中文标题】将 MKMapView 缩放到 MKAnnotationView 的框架【英文标题】:Zoom MKMapView to an MKAnnotationView's frame 【发布时间】:2013-03-16 19:13:50 【问题描述】:我有一个要放大的分组图钉。当然我知道大头针的坐标,并且有它的视图。我只想将地图缩放到正确的区域,以便集群完全展开,显示所有引脚(加上一点填充)。这样做的好方法是什么?
旁注: 在我的设置中,当缩放级别增加时,集群引脚将自动扩展为单个引脚,所以我很好。我需要知道的是如何根据集群引脚的框架和坐标将 MapView 设置为新区域。
【问题讨论】:
【参考方案1】:你可以使用:
mapView.showAnnotations(groupedAnnotations, animated: true)
此方法将自动放大和定位地图,以便所有注释都可见。
【讨论】:
【参考方案2】:首先删除组别针
[mapView removeAnnotation:groupAnnotation];
然后在集群中添加引脚
[mapView addAnnotations:clusterAnnotations];
然后确定要缩放到的区域
CLLocationDegrees minLat = 90;
CLLocationDegrees maxLat = -90;
CLLocationDegress minLong = 180;
CLLocationDegrees maxLong = -180
[clusterAnnotations enumerateUsingBlock:^(id<MKAnnotation> annotation, NSUInteger idx, BOOL *stop)
CLLocationCoordinate2D coordinate = annotation.coordinate;
minLat = MIN(minLat, coordinate.latitude);
maxLat = MAX(maxLat, coordinate.latitude);
minLong = MIN(minLong, coordinate.longitude);
maxLong = MAX(maxLong, coordinate.longitude);
CLLocationCoordinate2D center = CLLocationCoordinate2DMake((minLat + maxLat)/2.f, (minLong + maxLong)/2.f);
MKCoordinateSpan span = MKCoordinateSpanMake((maxLat - minLat)*1.25, (maxLong - minLong)*1.25); //1.25 is for padding
MKCoordinateRegion region = MKCoordinateRegionMake(center, span);
[mapView setRegion:[mapView regionThatFits:region] animated:YES];
【讨论】:
【参考方案3】:当用户点击集群引脚时,您将收到回调
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView)
现在您只需将您的MKAnnotationView
转换为MKClusterAnnotation
,然后您就可以访问其成员引脚的集合:
if let clustered = view.annotation as? MKClusterAnnotation
clustered.memberAnnotations.forEach (annotation) in
// Calculate region boundaries
尼克计算的完整解决方案:
if let clustered = view.annotation as? MKClusterAnnotation
var minLat = CLLocationDegrees(exactly: 90)!
var maxLat = CLLocationDegrees(exactly: -90)!
var minLong = CLLocationDegrees(exactly: 180)!
var maxLong = CLLocationDegrees(exactly: -180)!
clustered.memberAnnotations.forEach (annotation) in
let coordinate = annotation.coordinate
minLat = min(minLat, coordinate.latitude)
maxLat = max(maxLat, coordinate.latitude)
minLong = min(minLong, coordinate.longitude)
maxLong = max(maxLong, coordinate.longitude)
let centerLat = (minLat + maxLat) / 2
let centerLong = (minLong + maxLong) / 2
let center = CLLocationCoordinate2D(latitude: centerLat, longitude: centerLong)
let span = MKCoordinateSpan(latitudeDelta: (maxLat - minLat) * 1.5, longitudeDelta: (maxLong - minLong) * 1.5) // with some padding
let region = MKCoordinateRegion(center: center, span: span)
<your MKMapView>.setRegion(region, animated: true)
【讨论】:
以上是关于将 MKMapView 缩放到 MKAnnotationView 的框架的主要内容,如果未能解决你的问题,请参考以下文章