I have a basic map view with custom annotations that animate the map when clicked. Im getting the warnings below with my current approach. I’ve looked at a few other SO threads and I can’t get my code refactored and working with the functionality I have right now. I’d appreciate a quick heads up on how to use the new iOS 18 APIs.
‘init(coordinateRegion:interactionModes:showsUserLocation:userTrackingMode:annotationItems:annotationContent:)’ was deprecated in iOS 17.0: Use Map initializers that take a MapContentBuilder instead.’MapAnnotation’ was deprecated in iOS 17.0: Use Annotation along with Map initializers that take a MapContentBuilder instead
Copy paste-able code
import SwiftUI
import MapKit
struct LocationsView: View {
@EnvironmentObject private var vm: LocationsViewModel
@State var scale: CGFloat = 0.0
var body: some View {
ZStack {
mapLayer.ignoresSafeArea()
}
}
}
// --- WARNINGS HERE --
extension LocationsView {
private var mapLayer: some View {
Map(coordinateRegion: $vm.mapRegion,
annotationItems: vm.locations,
annotationContent: { location in
MapAnnotation(coordinate: location.coordinates) {
Circle().foregroundStyle(.red).frame(width: 50, height: 50)
.onTapGesture {
vm.showNextLocation(location: location)
}
}
})
}
}
class LocationsViewModel: ObservableObject {
@Published var locations: [LocationMap] // All loaded locations
@Published var mapLocation: LocationMap { // Current location on map
didSet {
updateMapRegion(location: mapLocation)
}
}
@Published var mapRegion: MKCoordinateRegion = MKCoordinateRegion() // Current region on map
let mapSpan = MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1)
init() {
let locations = LocationsDataService.locations
self.locations = locations
self.mapLocation = locations.first!
self.updateMapRegion(location: locations.first!)
}
private func updateMapRegion(location: LocationMap) {
withAnimation(.easeInOut) {
mapRegion = MKCoordinateRegion(
center: location.coordinates,
span: mapSpan)
}
}
func showNextLocation(location: LocationMap) {
withAnimation(.easeInOut) {
mapLocation = location
}
}
}
struct LocationMap: Identifiable {
var id: String = UUID().uuidString
let name: String
let cityName: String
let coordinates: CLLocationCoordinate2D
}
class LocationsDataService {
static let locations: [LocationMap] = [
LocationMap(name: "Colosseum", cityName: "Rome", coordinates: CLLocationCoordinate2D(latitude: 41.8902, longitude: 12.4922)),
LocationMap(name: "Pantheon", cityName: "Rome", coordinates: CLLocationCoordinate2D(latitude: 41.8986, longitude: 12.4769)),
LocationMap(name: "Trevi Fountain", cityName: "Rome", coordinates: CLLocationCoordinate2D(latitude: 41.9009, longitude: 12.4833))
]
}
struct SwiftfulMapAppApp: View {
@StateObject private var vm = LocationsViewModel()
var body: some View {
VStack {
LocationsView().environmentObject(vm)
}
}
}
#Preview(body: {
SwiftfulMapAppApp()
})