Magnus G
Magnus G

Reputation: 111

Change color of the selected marker with Swiftui and MapKit iOS 17?

I'm working with MapKit for SwiftUI using iOS 17 and I have placed markers on the map. Is there a way to change color of a selected marker?

This is minimalistic code that I have extracted from my project:

import SwiftUI
import MapKit
import SwiftData

struct ContentView: View {
    @Environment(\.modelContext) private var modelContext
    @Environment(LocationManager.self) var locationManager
    @State private var cameraPosition: MapCameraPosition = .userLocation(fallback: .automatic)
    @State private var selectedMarker: Placemark?
    @State private var markers = [Placemark]()      
       
    var body: some View {
        Map(position: $cameraPosition, selection: $selectedMarker) {
            UserAnnotation()
            ForEach(markers) { placemark in
                Group {
                    Marker(placemark.name, image: placemark.markerImage(), coordinate: placemark.coordinate)
                        .tint(Color.accentColor)
                }
                .tag(placemark)
            }
        }
    }
}

Upvotes: 0

Views: 154

Answers (1)

you could try something like this approach to change the color of the selected marker.

Works well for me, on macOS 15.3, using Xcode 16.2, target iOS-18, tested on real iOS device, MacCatalyst and MacOS.

.tint(placemark.id == selectedMarker?.id ? .yellow : .red)

Upvotes: 0

Related Questions