我有一个要放大的分组图钉。当然,我知道引脚的坐标,并且有它的视图。我只想将地图缩放到正确的区域,以便集群完全展开,显示所有引脚(加上一点填充)。这样做的好方法是什么?
旁注:
在我的设置中,当缩放级别增加时,集群引脚将自动扩展为单个引脚,所以我很好。我需要知道的是如何根据集群引脚的框架和坐标将 MapView 设置为新区域。
我有一个要放大的分组图钉。当然,我知道引脚的坐标,并且有它的视图。我只想将地图缩放到正确的区域,以便集群完全展开,显示所有引脚(加上一点填充)。这样做的好方法是什么?
旁注:
在我的设置中,当缩放级别增加时,集群引脚将自动扩展为单个引脚,所以我很好。我需要知道的是如何根据集群引脚的框架和坐标将 MapView 设置为新区域。
您可以使用:
mapView.showAnnotations(groupedAnnotations, animated: true)
此方法将自动放大并定位地图,以便所有注释都可见。
首先删除组别针
[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];
当用户点击集群引脚时,您将收到回调
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView)
现在您只需要将您的MKAnnotationView
to 转换为MKClusterAnnotation
,然后您就可以访问其成员 pin 的集合:
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)
}