I would suggest not to use this mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation)
method at all, instead have that setRegion logic defied in your updateUIView(_ view: MKMapView, context: Context)
for every small change in visible region of Map view we get this delegate method fired mapViewDidChangeVisibleRegion(_ mapView: MKMapView
So, I don't see the point in using didUpdate userLocation method, below snippet may give you some idea, please review:
struct MapView: UIViewRepresentable {
@Binding var centerCoordinate: CLLocationCoordinate2D
var currentLocation: CLLocationCoordinate2D?
var withAnnotation: MKPointAnnotation?
class Coordinator: NSObject, MKMapViewDelegate {
var parent: MapView
init(_ parent: MapView) {
self.parent = parent
}
func mapViewDidChangeVisibleRegion(_ mapView: MKMapView) {
if !mapView.showsUserLocation {
parent.centerCoordinate = mapView.centerCoordinate
}
}
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func makeUIView(context: Context) -> MKMapView {
let mapView = MKMapView()
mapView.delegate = context.coordinator
mapView.showsUserLocation = false
return mapView
}
func updateUIView(_ uiView: MKMapView, context: Context) {
if let currentLocation = self.currentLocation {
if let annotation = self.withAnnotation {
uiView.removeAnnotation(annotation)
}
uiView.showsUserLocation = true
let region = MKCoordinateRegion(center: currentLocation, latitudinalMeters: 800, longitudinalMeters: 800)
uiView.setRegion(region, animated: true)
} else if let annotation = self.withAnnotation {
uiView.removeAnnotations(uiView.annotations)
uiView.addAnnotation(annotation)
}
}
}
And set your current location like this
struct UserLocationView: View {
var parent: LocationView
init(_ parent: LocationView) {
self.parent = parent
}
var body: some View {
VStack {
HStack {
Spacer()
Button(action: {
if let location = locationFetcher.lastKnownLocation {
print("Your location is \(location)")
parent.currentLocation = location
withAnimation {
parent.hideAddButton = true
}
} else {
print("Your location is unknown")
}
}) {
Image(systemName: "location.circle.fill")
.padding()
.background(Color.blue.opacity(0.75))
.foregroundColor(.white)
.font(.title)
.clipShape(Circle())
.rotationEffect(.degrees(45))
.padding(.trailing)
}
}
}
}
}
Hope this will help, code to entire project can be found here