Just in case anyone else is interested, here is this this answer translated to Swift in a simple ViewController
. I just left out .FollowWithCourse
to copy the behavior of MKUserTrackingBarButtonItem
.
class ViewController: UIViewController, MGLMapViewDelegate {
@IBOutlet weak var map: MGLMapView!
@IBOutlet weak var toolbar: UIToolbar!
override func viewDidLoad() {
super.viewDidLoad()
map.delegate = self
map.setCenterCoordinate(CLLocationCoordinate2D(latitude: 40.7326808, longitude: -73.9843407), zoomLevel: 12, animated: false)
let trackingButton = UIBarButtonItem(image: UIImage(named: "TrackingLocationOffMask"), style: UIBarButtonItemStyle.Plain, target: self, action: "trackingButtonChanged")
toolbar.items!.insert(trackingButton, atIndex: 0)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func mapView(mapView: MGLMapView, didChangeUserTrackingMode mode: MGLUserTrackingMode, animated: Bool) {
var image: String = "TrackingLocationOffMask.png"
switch (mode) {
case .Follow:
image = "TrackingLocationMask.png"
break
case .FollowWithHeading:
image = "TrackingHeadingMask.png"
break
default:
break
}
UIView.animateWithDuration(0.25, animations: {
(self.toolbar.items![0] as UIBarButtonItem).image = UIImage(named: image)
})
}
func trackingButtonChanged() {
var mode: MGLUserTrackingMode = .Follow
switch (map.userTrackingMode) {
case .Follow:
mode = .FollowWithHeading
break
case .FollowWithHeading:
mode = .None
break
default:
break
}
map.userTrackingMode = mode
}
}
The images are here at mapbox-gl-native on GitHub.