I am quite new to Swift and SwiftUI, and I want to add a user tracking button on top of the mapview, so user's current location can be back in the center of the screen when tapped. I have already have the mapview and the button, but failed to make it work.
here is the ContentView.swift file, and I am stuck at the place with ****:
import SwiftUI
import MapKit
struct ContentView: View {
var body: some View {
ZStack {
MapView(locationManager: $locationManager)
.edgesIgnoringSafeArea(.bottom)
HStack {
Spacer()
VStack {
Spacer()
Button(action: {
******
}) {
Image(systemName: "location")
.imageScale(.small)
.accessibility(label: Text("Locate Me"))
.padding()
}
.background(Color.white)
.cornerRadius(10)
.padding()
}
}
}
}
And here is the MapView.swift:
import SwiftUI
import MapKit
import CoreLocation
import ECMapNavigationAble
struct MapView: UIViewRepresentable, ECMapNavigationAble{
var locationManager = CLLocationManager()
func makeUIView(context: UIViewRepresentableContext<MapView>) -> MKMapView {
MKMapView()
}
func updateUIView(_ view: MKMapView, context: UIViewRepresentableContext<MapView>){
view.showsUserLocation = true
view.isPitchEnabled = false
self.locationManager.requestAlwaysAuthorization()
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
}
if let userLocation = locationManager.location?.coordinate {
let userLocationEC = ECLocation(coordinate : userLocation, type: .wgs84)
let viewRegion = MKCoordinateRegion(center: userLocationEC.gcj02Coordinate, latitudinalMeters: 200, longitudinalMeters: 200)
view.userTrackingMode = .follow
view.setRegion(viewRegion, animated: true)
}
DispatchQueue.main.async{
self.locationManager.startUpdatingLocation()
}
}
}