Update Swift 5.9:
mapType is deprecated. Now using preferredConfiguration.
Here is an example using UIAlertController:
//Add button to navigationbar
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Change Map Type", style: .plain, target: self, action: #selector(mapTypeTapped))
//Setup AlertController
@objc func mapTypeTapped(){
let ac = UIAlertController(title: "Choose map type:", message: nil, preferredStyle: .actionSheet)
ac.addAction(UIAlertAction(title: "Hybrid", style: .default, handler: setMapType))
ac.addAction(UIAlertAction(title: "Satellite", style: .default, handler: setMapType))
ac.addAction(UIAlertAction(title: "Standard", style: .default, handler: setMapType))
ac.addAction(UIAlertAction(title: "Cancel", style: .cancel))
present(ac, animated: true)
}
//Switch the action.title
func setMapType(_ action: UIAlertAction){
switch action.title {
case "Hybrid":
if #available(iOS 16.0, *) {
mapView.preferredConfiguration = MKHybridMapConfiguration(elevationStyle: .realistic)
} else {
mapView.mapType = .hybrid
}
case "Satellite":
if #available(iOS 16.0, *) {
mapView.preferredConfiguration = MKImageryMapConfiguration(elevationStyle: .realistic)
} else {
mapView.mapType = .satellite
}
default:
if #available(iOS 16.0, *) {
mapView.preferredConfiguration = MKStandardMapConfiguration(elevationStyle: .realistic)
} else {
mapView.mapType = .standard
}
}
}