平移到新的mapView注释位置 - 不缩放

时间:2018-04-11 19:56:26

标签: mkmapview swift4 mkannotation mkannotationview

使用mapView.addAnnotation向我的mapView添加注释时,mapView.setRegion会正确设置动画并显示地图的中心和地图。跨度。

但是当添加新注释然后调用mapView.setRegion时,视图将从非常宽的范围开始,然后动画/放大到新的中心&跨度。

我想知道是否有办法将PAN从上一个区域扩展到新区域(中心和跨度),而不是开始缩小,然后再一次缩放。

mapView.setRegion每次都会从这里开始缩放: Image

我定义了2个自定义类:MarkAnnotation& MarkAnnotationView

class MarkAnnotation : NSObject, MKAnnotation {
    var coordinate: CLLocationCoordinate2D
    var title: String?
    var subtitle: String?

    init(coordinate: CLLocationCoordinate2D, title: String, subtitle: String) {
        self.coordinate = coordinate
        self.title = title
        self.subtitle = subtitle
    }
}

class MarkAnnotationView: MKAnnotationView {
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
    super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
        guard let markAnnotation = self.annotation as? MarkAnnotation else { return }
        image = UIImage(named: "customAnnotation")
    }
}

和我的MKMapViewDelegate

func addMarkAnnotation() {
    for mark in marks {
        let markName : String = mark.name
        let markLat : Double = mark.lat
        let markLon : Double = mark.lon
        let markLL = CLLocationCoordinate2DMake(markLat, markLon)
        let markAnnotation = MarkAnnotation(coordinate:markLL, title:markNumStr, subtitle: markName)
        mapView.addAnnotation(markAnnotation)
    }
}

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    let annotationView = MarkAnnotationView(annotation: annotation, reuseIdentifier: "MarkView")
    annotationView.canShowCallout = true
    return annotationView
}

func centerMapOnLocation(location:CLLocation, span:Double) {
    let mapSpan = MKCoordinateSpanMake(0.2, 0.2)
    let recenterRegion = MKCoordinateRegion(center: location.coordinate, span: mapSpan)
    mapView.setRegion(recenterRegion, animated: true)
}

然后在ViewController中,当用户按下按钮时,会在指定的纬度/经度处添加标记

func addMarkBtnPressed() {
    // .... (have not shown : conversion of text fields from String to Double, adding Mark to marks array, etc ) ... All this works fine

    addMarkAnnotation()

    let mapCenter = CLLocation(latitude: markLat, longitude: markLon)
    centerMapOnLocation(location: mapCenter, span: span)
}

1 个答案:

答案 0 :(得分:0)

请尝试以下代码:

func centerMapOnLocation(location:CLLocation, span:Double) {
    let mapSpan = mapView.region.span
    let recenterRegion = MKCoordinateRegion(center: location.coordinate, span: mapSpan)
    mapView.setRegion(recenterRegion, animated: true)
}