I have a map that shows the users location where the user's location is signified by a circle. I want to add an animation centered around the users location on the map, for example a radar that looks like it is searching.
I have tried adding an overlay but cannot get it to center around the user's location. The overlay stays in the center of the map view instead of staying with the dot representing the users location.
Here is a simplified version of my map implementaion
@StateObject private var viewModel = ContentViewModel()
var body: some View {
VStack{
Map(coordinateRegion: $viewModel.region, showsUserLocation: true)
.overlay(
Circle()
.stroke(Color.red, lineWidth: 1)
.frame(width: radius * 2, height: radius * 2)
.animation(.easeOut(duration: 2))
.opacity(circleIsVisible ? 1 : 0)
)
.onAppear{
viewModel.requestAllowOnceLocationPermission()
}
}
}
final class ContentViewModel: NSObject, ObservableObject, CLLocationManagerDelegate {
@Published var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 45.032740, longitude: -80.6983), span: MKCoordinateSpan(latitudeDelta: 0.03, longitudeDelta: 0.03))
@ObservedObject var mapRegion = MapRegion(region: MKCoordinateRegion())
let locationManager = CLLocationManager()
@State var longitude = 0.0
@State var latitude = 0.0
@Published var userLocation: CLLocationCoordinate2D?
override init(){
super.init()
locationManager.delegate = self
}
// function that asks for user permission to use location
func requestAllowOnceLocationPermission(){
locationManager.requestWhenInUseAuthorization()
locationManager.requestLocation()
}
// get the user's last location
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let latestLocation = locations.first else {
return
}
// Update the userLocation property with the latest coordinate
userLocation = latestLocation.coordinate
// Make sure we are on the main thread to update the region
DispatchQueue.main.async {
self.region = MKCoordinateRegion(center: latestLocation.coordinate, span: MKCoordinateSpan(latitudeDelta: 0.03, longitudeDelta: 0.03))
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("failed with error")
}
}