Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Button to center view to user location using MapKit

Tags:

ios

swift

mapkit

Is there a dedicated button in MapKit that centers camera over user location? Or do I have to do it manually creating button and toggle mapView.showsUserLocation = true?

like image 865
Xernox Avatar asked Jan 14 '16 14:01

Xernox


People also ask

How do I use MapKit in swift 5?

Go to the storyboard. Drag a MapKit View to the main View. Give the MapKit View the same size as the main View. Select the MapKit View and go to the Pin button from the Auto Layout button on the bottom-right of the Storyboard and fill in the following values.


Video Answer


2 Answers

This way runs well (Swift), and you can customize the button:

class YourViewController{
   ...
   @IBOutlet weak var mapView:MKMapView
   ...

   override func viewDidLoad() {
      super.viewDidLoad()
      ...
      addMapTrackingButton()
   }

   func addMapTrackingButton(){
      let image = UIImage(named: "trackme") as UIImage?
      let button   = UIButton(type: UIButtonType.System) as UIButton
      button.frame = CGRectMake(5, 5, 35, 35)
      button.setImage(image, forState: .Normal)
      button.backgroundColor = .clearColor()
      button.addTarget(self, action: #selector(YourViewController.centerMapOnUserButtonClicked), forControlEvents:.TouchUpInside)
      self.mapView.addSubview(button)
   }

   func centerMapOnUserButtonClicked() {
      self.mapView.setUserTrackingMode( MKUserTrackingMode.Follow, animated: true)
   }
   ...
}

Swift 4:

func addMapTrackingButton(){
    let image = UIImage(named: "trackme") as UIImage?
    let button   = UIButton(type: UIButtonType.custom) as UIButton
    button.frame = CGRect(origin: CGPoint(x:5, y: 25), size: CGSize(width: 35, height: 35))
    button.setImage(image, for: .normal)
    button.backgroundColor = .clear
    button.addTarget(self, action: #selector(ViewController.centerMapOnUserButtonClicked), for:.touchUpInside)
    mapView.addSubview(button)
}

@objc func centerMapOnUserButtonClicked() {
    mapView.setUserTrackingMode(MKUserTrackingMode.follow, animated: true)
}
like image 174
Viker Avatar answered Oct 23 '22 20:10

Viker


Being late, ahah, but I just found the function :

CLLocationManager.requestLocation()

So once you properly set your locationManager (with requestAlwaysAuthorization) you can call it wherever you want to center your map on your own location :)

like image 27
Adèle Dunand Avatar answered Oct 23 '22 21:10

Adèle Dunand