Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

moving MapView programmatically

I have a mapView in which I show a location (represented by custom pin) as seen in screenshot enter image description here

How can I move the mapView so that the icon is visible completely?

like image 752
DanielR Avatar asked Sep 04 '25 04:09

DanielR


1 Answers

To achieve this you first need to calculate the point on screen view where you want to scroll (In your case let assume its 20 pixel up to the annotation marker), Then you need to covert this point to Map location so that you can move map center to that location ;-). Following is the code written in Swift in MKMapView delegate methods where annotation gets tapped.

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
}
like image 187
Gurjit Singh Avatar answered Sep 06 '25 15:09

Gurjit Singh