I found the code to annotate on map after running the code but unable to combine with my main code. My main code uses map( .... ) to int the map on mapkit but the annotation code is using 'MapView' as shown below,
MapView version of int Map on SwiftUI
MapView(centerCoordinate: $centerCoordinate, annotations: locations)
.edgesIgnoringSafeArea(.all)
Map version of int Map on SwiftUI
Map(coordinateRegion: $viewModel.region,
interactionModes: .all,
showsUserLocation: true,
annotationItems: annotationItems)
The code I got is able to take in user values in Double (Lat and Long) and annotate on the map.
I am more comfortable using the map(...) setup but the annotation I got is from mapView which is another set up.
I have difficulties combing them together.
I can annotate on the map before running the code ,but what I want is update after int the map and I cannot seem to find the code to annotate for the map( ...) format.
The mapview(...) verision is ,
Button(action: {
let savedLat = Double(textFieldLat) // Lat value
let savedLong = Double(textFieldLong) // Long value
let newLocation = MKPointAnnotation()
newLocation.coordinate = CLLocationCoordinate2D(latitude: savedLat ?? 0, longitude: savedLong ?? 0)
self.locations.append(newLocation)
})
Update the map
struct MapView: UIViewRepresentable{
...
...
...
func updateUIView(_ view: MKMapView, context: Context) {
if annotations.count != view.annotations.count {
view.addAnnotations(annotations)
}
}
}
Thank you for your time!
The difference between Map and MKMapView
Mapis a native SwiftUI view that embeds a map interface according to SwiftUI's Map doc, whereasMKMapViewis a class for an embeddable map interface (doc). I don't think you can combine them - this post in Apple's dev forums suggests usingMKMapViewifMapis unable to meet your needs, or submitting a feature request.In practice,
Mapis easier to use and can be dynamically updatedMap is designed to be simpler to use. I was also looking for how to add annotation markers to
MapXCode's MapKit and SwiftUI tutorials, the official documentation lacks helpful examples.Here's a code sample of how I was able to initialize then dynamically update the marker based on passing in a coordinate. If you need to render multiple markers, you could instead add additional items to the
markerslist and then iterate over each of them like this example in the apple forums.