以编程方式移动MapView

3

我有一个mapView,其中显示了一个位置(由自定义图标表示),如屏幕截图所示:

enter image description here

如何移动mapView,以便完全可见图标?


这个对我很有帮助:https://dev59.com/z1rUa4cB1Zd3GeqPiEW6 - DanielR
1个回答

2
为了实现这一点,首先需要计算屏幕视图上您想要滚动的点(在您的情况下假设它是批注标记上方20像素),然后您需要将此点转换为地图位置,以便您可以将地图中心移动到该位置 ;-)。 以下是在MKMapView委托方法中单击注释时编写的Swift代码。
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
    let pinLocation = view.annotation.coordinate

    let currentCoordinates = mapView.centerCoordinate // Temporary saved map current center position

    // Temp set map center position to pin location
    mapView.centerCoordinate = pinLocation

    let viewCenter = self.view.center
    let fakecenter = CGPoint(x: viewCenter.x, y: viewCenter.y - 20) // point just up to the center point

    // convert calculetd point to map location co-ordinates
    let coordinate: CLLocationCoordinate2D = mapView.convert(fakecenter, toCoordinateFrom: self.view)

    // reset to previous potion so thet animation start from that
    mapView.centerCoordinate = currentCoordinates
    self.mapView.setCenter(coordinate, animated: true) // change the new center
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接