How to add multiple Pins (MapMarkers) to the Map View?

427 Views Asked by At

Im trying to pin the locations on the mapview but the errors keep coming up

I tried adding all the PinItem to the annotationItems but that doesn't work

struct Store_locator_page: View {

    struct PinItem: Identifiable{
        let id = UUID()
        let coordinate: CLLocationCoordinate2D
    }

    @State var region = MKCoordinateRegion(center:.init(latitude: -32.5, longitude: 115.75),latitudinalMeters: 1000, longitudinalMeters: 1000)

    let locations = [
        PinItem(coordinate: .init(latitude: -32.5, longitude: 115.75)),
        PinItem(coordinate: .init(latitude: -32.7, longitude: 115.9)),
        PinItem(coordinate: .init(latitude: -32.6, longitude: 115.8)),
        PinItem(coordinate: .init(latitude: -32.4, longitude: 115.7))
    ]

    var body: some View {
        ScrollView{
            Map(coordinateRegion : $region,
                interactionModes: [],
                showsUserLocation: true,
                userTrackingMode: nil,
                annotationItems: [PinItem(coordinate: .init(latitude: -32.5, longitude: 115.75))]
            ) { item in
                MapMarker(coordinate: item.coordinate)
            }
        }
    }
}
1

There are 1 best solutions below

0
Andy Jazz On

Use the following technique to append multiple pins to the Map view.

import SwiftUI
import MapKit

extension CLLocationCoordinate2D: Identifiable {
    public var id: String {
        "\(latitude)-\(longitude)"
    }
}

struct Place: Identifiable {
    var id = UUID()
    let name: String
    let coordinate: CLLocationCoordinate2D
    let color: Color
}

enter image description here

struct ContentView : View {
    
    @State var region = MKCoordinateRegion(center:.init(latitude: -32.5,
                                                       longitude: 115.75),
                                               latitudinalMeters: 100_000,
                                              longitudinalMeters: 100_000)
    let annotations = [
        Place(name: "Andy's Place",
        coordinate: .init(latitude: -32.5, longitude: 115.75),
             color: .black),
        
        Place(name: "Jane's Place",
        coordinate: .init(latitude: -32.7, longitude: 115.9),
             color: .pink),
        
        Place(name: "Rick's Place",
        coordinate: .init(latitude: -32.6, longitude: 115.8),
             color: .indigo),
        
        Place(name: "Lola's Place",
        coordinate: .init(latitude: -32.4, longitude: 115.7),
             color: .orange)
    ]
    
    var body: some View {

        Map(coordinateRegion: $region, annotationItems: annotations) {

            MapMarker(coordinate: $0.coordinate, tint: $0.color)
        }
        .ignoresSafeArea()
    }
}