我试图在给定的MKMapRect中对注释/坐标进行居中。我首先创建了rect,它是地图视图和另一个视图之间的可见区域。然后将这个rect转换为与地图视图成比例的rect,以便正确显示它。然后,为了测试目的,我将注释设置为显示在左上角。
if let annotation = annotation {
let visibleRect = CGRectMake(0, 0, CGRectGetWidth(mapView.frame), CGRectGetMinY(stackViewController.view.frame))
let convertedRect = mapView.convertRect(visibleRect, toView: mapView)
let convertedMapRect = MKMapRectMake(Double(convertedRect.origin.x), Double(convertedRect.origin.y), Double(convertedRect.width), Double(convertedRect.height))
let point = MKMapPointForCoordinate(annotation.coordinate)
let pointRect = MKMapRectMake((MKMapRectGetMidX(convertedMapRect) - point.x) / 2, (MKMapRectGetMidY(convertedMapRect) - point.y) / 2, convertedMapRect.size.width, convertedMapRect.size.height)
mapView.setVisibleMapRect(pointRect, animated: true)
mapView.selectAnnotation(annotation, animated: true)
}此代码运行良好,并将按预期在左上角显示注释。然而,当我试图把注释放在中间,而不是把它放在左上角时,地图是在海中,而不是在纽约。这通常是因为点是无效的。记录了rect后,在执行中心计算时,它返回的x值和y值太小。我认为这是因为像素数没有被正确地转换到地图的坐标系统。这就是为什么,我怎样才能把它放大呢?
if let annotation = annotation {
let visibleRect = CGRectMake(0, 0, CGRectGetWidth(mapView.frame), CGRectGetMinY(stackViewController.view.frame))
let convertedRect = mapView.convertRect(visibleRect, toView: mapView)
let convertedMapRect = MKMapRectMake(Double(convertedRect.origin.x), Double(convertedRect.origin.y), Double(convertedRect.width), Double(convertedRect.height))
let point = MKMapPointForCoordinate(annotation.coordinate)
let pointRect = MKMapRectMake((MKMapRectGetMaxX(convertedMapRect) - point.x) / 2, (MKMapRectGetMaxX(convertedMapRect) - point.y) / 2, convertedMapRect.size.width, convertedMapRect.size.height)
mapView.setVisibleMapRect(pointRect, animated: true)
mapView.selectAnnotation(annotation, animated: true)
}发布于 2016-02-27 20:58:50
我在这里偶然发现了这篇文章,这对我有很大的帮助:Centering MKMapView on spot N-pixels below pin。
正如答案中提到的那样,您应该通过将目标点从地图视图转换到视图控制器的视图中,从而计算出目标点,其框架或多或少是标准化的。
// define the rect in which to center the annotation
let visibleRect = CGRectMake(0, 0, CGRectGetWidth(view.frame), 200)
centerAnnotationInRect(someAnnotation, rect: visibleRect)
func centerAnnotationInRect(annotation: MKAnnotation, rect: CGRect) {
guard let mapView = mapView else {
return
}
let visibleCenter = CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect))
let annotationCenter = mapView.convertCoordinate(annotation.coordinate, toPointToView: view)
let distanceX: CGFloat = visibleCenter.x - annotationCenter.x
let distanceY = visibleCenter.y - annotationCenter.y
mapView.scrollWithOffset(CGPoint(x: distanceX, y: distanceY), animated: true)
}https://stackoverflow.com/questions/35509410
复制相似问题