History
Loading...
Loading...
September 15, 2025
Map with custom annotations, wrap your annotation views in MapAnnotation and use @State to track the selected annotation for better performance. Use mapStyle(.standard(elevation: .realistic)) for iOS 17+ to enable 3D terrain visualization.This pattern uses Identifiable locations with MapAnnotation for clean annotation rendering. The selected location triggers a sheet presentation, keeping map interactions separate from detail views. Using @State for region and selection ensures proper SwiftUI state management.
struct LocationPin: Identifiable {
let id = UUID()
let coordinate: CLLocationCoordinate2D
let title: String
let subtitle: String
}
struct MapView: View {
@State private var locations = [
LocationPin(coordinate: CLLocationCoordinate2D(latitude: 37.7749, longitude: -122.4194), title: "San Francisco", subtitle: "Golden Gate City"),
LocationPin(coordinate: CLLocationCoordinate2D(latitude: 40.7128, longitude: -74.0060), title: "New York", subtitle: "The Big Apple")
]
@State private var selectedLocation: LocationPin?
@State private var region = MKCoordinateRegion(
center: CLLocationCoordinate2D(latitude: 39.8283, longitude: -98.5795),
span: MKCoordinateSpan(latitudeDelta: 20, longitudeDelta: 20)
)
var body: some View {
Map(coordinateRegion: $region, annotationItems: locations) { location in
MapAnnotation(coordinate: location.coordinate) {
Button {
selectedLocation = location
} label: {
Image(systemName: "mappin.circle.fill")
.foregroundColor(.red)
.font(.title2)
.background(Color.white.clipShape(Circle()))
}
}
}
.sheet(item: $selectedLocation) { location in
LocationDetailView(location: location)
}
}
}Identifiable conformance enables efficient SwiftUI diffing and animations. Separating map interaction from detail presentation follows single responsibility principle. MapAnnotation provides better performance than overlay-based approaches and integrates seamlessly with SwiftUI's declarative syntax.