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
?
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.
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)
}
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With