只有在靠近屏幕边缘时,如何将地图置于注释视图中心?

在我的swift应用程序中,我正在使用MapKit ,我正在向地图添加一些注释。

目前,由于这个问题: 尝试获取iOS MKCoordinateSpan的跨度大小(以米为单位)我设法创建了一个function,当用户按下它时,我的地图会在注释中居中。 这是它的代码:

 let span = mapView.region.span let centerView = mapView.region.center let loc1 = CLLocation(latitude: centerView.latitude - span.latitudeDelta * 0.5, longitude: centerView.longitude) let loc2 = CLLocation(latitude: centerView.latitude + span.latitudeDelta * 0.5, longitude: centerView.longitude) let loc3 = CLLocation(latitude: centerView.latitude, longitude: centerView.longitude - span.longitudeDelta * 0.5) let loc4 = CLLocation(latitude: centerView.latitude, longitude: centerView.longitude + span.longitudeDelta * 0.5) let metersInLatitude = loc1.distance(from: loc2) let metersInLongitude = loc3.distance(from: loc4) let center:CLLocationCoordinate2D = (MyCustomAnnotation?.coordinate)! let coordinateRegion = MKCoordinateRegionMakeWithDistance(center, metersInLatitude, metersInLongitude) mapView.setRegion(coordinateRegion, animated: true) 

并且工作正常 – 每当用户点击任何MyCustomAnnotation ,它将使地图居中,同时保持当前的缩放级别。

我想稍微改变一下这个代码,所以只有当点接近屏幕的四个边缘之一时,它才会将地图集中在点上。 当注释点位于靠近屏幕中心的某个位置时 – 我们不应将地图居中。 我该怎么做? 我想过(以某种方式)检查MyCustomAnnotation?.coordinate和由这四个点loc1loc2loc3loc4设置的区域之间的区别,但是我不知道如何处理它。 你能帮帮我吗?

我不会将注释的位置与所有四个边缘进行比较,而是检查距中心位置的距离。

 let distance = center.distanceFromLocation(annotationLocation) 

如果此距离大于某个半径,则注释接近其中一个边。

 if distance > radius { //center annotation } 

可以从区域跨度计算半径。

 let radius = min(region.span.longitudeDelta, region.span.latitudeDelta) * 0.3