SwiftUI | Integrate a map & display annotations in iOS 14
Thanks to the new APIs of SwiftUI 2.0, we can now present a map natively with the Map() method. Let’s see how to present one with some annotations.
Difficulty: Beginner | Easy | Normal | Challenging
Environment : Xcode 12 & SwiftUI
Create a new Xcode project
Open Xcode and create a new project, select App as a template, SwiftUI interface, and let’s call our project MapLocation.
Let’s create our map
The new SwiftUI 2.0 APIs make it really easy to integrate a map in our project, it’s enough to import the framework and call the Map() method.
Import the MapKit framework at the top of your ContentView.Swift file:
Also, Add this region parameter before the body variable but after the struct:
We used the coordinates of Paris, Now you need to recall this coordinate inside the map method. Copy/paste the following code inside the body:
Now, run your app, a map will appear full screen and will locate you in Paris!
Next step: Add some annotations
Create a new Swift file and call it annotation:
Copy/paste the following code inside the annotation.Swift file that you just created:
We are going to use this file to display our annotation, we created a struct of our annotation with an identifier, a title, and two-dimensional coordinates. Then, we add a few locations: Tour Eiffel, Sacré Coeur, and Arc de Triomphe with their respective coordinates.
Let’s display our annotations
Go back to your ContentView.Swift file and make the connection to annotation.Swift with the following line of code:
Now, you just have to replace the current Map method with the following one which contains the annotation method inside the parenthesis:
Run your app
You can now run your app and 3 pins will be displayed on the map: Tour Eiffel, Sacré Coeur, and Arc de Triomphe.
Conclusion:
Thanks for reading! In a few lines of code, we added a map using SwiftUI 2.0. It was really straightforward to set it up and add a few annotations. Next Step: try to integrate core location to locate the user in real-time. If you have any questions, leave me a comment and if you find it useful, share it with someone who might also find it interesting!
I’m always happy to have a chat and collaborate at hello@sullivandecarli.com. Consider subscribing to enjoy unlimited access to my articles and all of Medium through my referral link.