问题
So....in my coordinator--which conforms to the mapbox delegate protocol, I can just do:
mapView.setCenter(mapView.userLocation!.coordinate, zoomLevel: 13, animated: true)
and this function works fine in the coordinator or when it is called in the mapView class. The only problem is I don't know how to pass this mapView instance around (specifically back into ContentView where I want to have a button that does the same thing). I also have a LocationManager struct but I don't know how much use that would be here. Is the passing of the MapView instance the simplest way to accomplish what I'd like to do?
Thank you in advance!
回答1:
Here is a demo of solution (based on MapKit, but it not important for idea). Tested with Xcode 12.
struct DemoActionToMapView: View {
@State private var centerToUser: () -> () = {}
var body: some View {
VStack {
Button("Center", action: centerToUser)
MapView { map in
self.centerToUser = {
map.setCenter(map.userLocation.coordinate, animated: true)
}
}
}
}
}
struct MapView: UIViewRepresentable {
var configure: (MKMapView) -> () = { _ in }
func makeUIView(context: Context) -> MKMapView {
let map = MKMapView()
DispatchQueue.main.async {
configure(map)
}
return map
}
func updateUIView(_ uiView: MKMapView, context: Context) {
}
}
来源:https://stackoverflow.com/questions/62844158/button-in-contentview-that-zooms-to-current-location-on-mapbox-map