Learning Time : 30min

My Github : Bucket List Source Code

My Note index link

day69.png

KeyWords

Integrating MapKit with SwiftUI

MapKit for SwiftUI | Apple Developer Documentation

Import MapKit and Set Up the Initial Map

import MapKit

@State private var mapRegion = MKCoordinateRegion(
    center: CLLocationCoordinate2D(latitude: 51.5, longitude: -0.12),
    span: MKCoordinateSpan(latitudeDelta: 0.2, longitudeDelta: 0.2)
)

Create a Custom Location Data Type

struct Location: Identifiable {
    let id = UUID()
    let name: String
    let coordinate: CLLocationCoordinate2D
}

Define Locations and Add Annotations

let locations = [
    Location(name: "Buckingham Palace", coordinate: CLLocationCoordinate2D(latitude: 51.501, longitude: -0.141)),
    Location(name: "Tower of London", coordinate: CLLocationCoordinate2D(latitude: 51.508, longitude: -0.076))
]

Add Annotations to the Map

Map(coordinateRegion: $mapRegion, annotationItems: locations) { location in
    MapAnnotation(coordinate: location.coordinate) {
        MapMarker(coordinate: location.coordinate)
    }
}

Map(coordinateRegion: $mapRegion, annotationItems: locations) { location in
    MapAnnotation(coordinate: location.coordinate) {
        Circle()
            .stroke(Color.red, lineWidth: 3)
            .frame(width: 44, height: 44)
            .onTapGesture {
                print("Tapped on \\(location.name)")
            }
    }
}

Map(coordinateRegion: $mapRegion, annotationItems: locations) { location in
    MapAnnotation(coordinate: location.coordinate) {
        VStack {
						Circle()
                .stroke(.red, lineWidth: 3)
                .frame(width: 44, height: 44)
                .onTapGesture {
                    print("Tapped on \\(location.name)")
                }

            Text("\\(location.name)")
                .foregroundColor(.red)
        }
    }
}