仅当地图靠近屏幕边缘时,如何才能将地图置于注释视图的中心?

how can I center my map on the annotation view only when it is close to the edge of the screen?

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

目前,由于这个问题:Trying to get the span size in meters for an iOS MKCoordinateSpan 我设法创建了一个功能,当用户按下它时,它使我的地图在注释上居中。这是它的代码:

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