In this post, we’ll learn how to:
- Add Markers
- Customize Annotations
- Add Map Buttons
Add Markers
Let’s see how to add a marker to both Berkeley and Stanford Universities.
First, we’ll create a structure for our locations:
struct Place: Identifiable {
let id = UUID()
var name: String
var coordinates: CLLocationCoordinate2D = .init(latitude: 0.0, longitude: 0.0)
}
The struct implements the Identifiable protocol because we need to define an ID for each element. This is especially crucial as we want to use an array of places, and it’s necessary to uniquely identify an element when iterating over the array. The other fields of the struct should be self-explanatory.
Now, let’s see how to display these two places on the map. We’ll set the center of the map over San Mateo, CA, as it’s equidistant from both locations. Then, for each place, we’ll add a marker on the map:
struct ContentView: View {
let locationManager = CLLocationManager()
@State var position: MapCameraPosition = .region(MKCoordinateRegion(
center: .init(latitude: 37.554169, longitude: -122.313057),
span: .init(latitudeDelta: 0.7, longitudeDelta: 0.7)
))
var…