Button in ContentView that zooms to current location on MapBox map?

北城余情 提交于 2021-01-27 18:32:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!