Updated 11 December 2023
In this blog, we will learn about how to integrate Apple Maps in Swift.
Apple provides MKMapView class for working with map. This class displays maps and provides interface to navigate map content.
Please follow below steps to add Apple map in your project.
Step 1 : Add MapView in your UIViewController. And add outlet of MapView to UIViewController.
Step 2: Add MapKit Framework to your project.
Now, you can run the code and see Map on your screen.
To get the Current Location please continue the steps.
Step 3: Import MapKit in you UIViewController
Step 4 : Now setup MKMapViewDelegate, CLLocationManagerDelegate in your code.
1 2 3 4 5 6 7 8 |
import MapKit class ViewController: UIViewController, MKMapViewDelegate { @IBOutlet weak var mapView: MKMapView! override func viewDidLoad() { super.viewDidLoad() mapView.delegate = self } } |
Step 5: Now add a Current location button and make an action of that button and add below code.
1 2 3 4 5 6 7 8 9 10 11 |
if (CLLocationManager.locationServicesEnabled()) { if locationManager == nil { locationManager = CLLocationManager() } locationManager?.requestWhenInUseAuthorization() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestAlwaysAuthorization() locationManager.startUpdatingLocation() isCurrentLocation = true } |
Step 6: After that add didUpdateLocations function from CLLocationManagerDelegate and add below code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if !isCurrentLocation { return } isCurrentLocation = false let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude) let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01)) self.mapView.setRegion(region, animated: true) if self.mapView.annotations.count != 0 { annotation = self.mapView.annotations[0] self.mapView.removeAnnotation(annotation) } let pointAnnotation = MKPointAnnotation() pointAnnotation.coordinate = location!.coordinate pointAnnotation.title = "" mapView.addAnnotation(pointAnnotation) } |
Step 7: Must add NSLocationWhenInUseUsageDescription and NSLocationAlwaysUsageDescription in your info.Plist file
So please follow the above step and and if you have any issue or suggestion you can leave your query/suggestion in the comment section I will try to solve that.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.