gpt4 book ai didi

mapkit - Swiftui如何使用MKOverlayRenderer?

转载 作者:行者123 更新时间:2023-12-03 21:18:51 26 4
gpt4 key购买 nike

我想在 map 上画一条路线。

但不使用委托(delegate)的结构。

struct MapView : UIViewRepresentable {
}

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
}

我能怎么做?

最佳答案

如果你想mapView(_:rendererFor:),你需要指定一个代表。被称为:

struct MapView: UIViewRepresentable {
@Binding var route: MKPolyline?
let mapViewDelegate = MapViewDelegate()

func makeUIView(context: Context) -> MKMapView {
MKMapView(frame: .zero)
}

func updateUIView(_ view: MKMapView, context: Context) {
view.delegate = mapViewDelegate // (1) This should be set in makeUIView, but it is getting reset to `nil`
view.translatesAutoresizingMaskIntoConstraints = false // (2) In the absence of this, we get constraints error on rotation; and again, it seems one should do this in makeUIView, but has to be here
addRoute(to: view)
}
}

private extension MapView {
func addRoute(to view: MKMapView) {
if !view.overlays.isEmpty {
view.removeOverlays(view.overlays)
}

guard let route = route else { return }
let mapRect = route.boundingMapRect
view.setVisibleMapRect(mapRect, edgePadding: UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10), animated: true)
view.addOverlay(route)
}
}

class MapViewDelegate: NSObject, MKMapViewDelegate {
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let renderer = MKPolylineRenderer(overlay: overlay)
renderer.fillColor = UIColor.red.withAlphaComponent(0.5)
renderer.strokeColor = UIColor.red.withAlphaComponent(0.8)
return renderer
}
}

像这样使用:

struct ContentView : View {
@State var route: MKPolyline?

var body: some View {
MapView(route: $route)
.onAppear {
self.findCoffee()
}
}
}

private extension ContentView {
func findCoffee() {
let start = CLLocationCoordinate2D(latitude: 37.332693, longitude: -122.03071)
let region = MKCoordinateRegion(center: start, latitudinalMeters: 2000, longitudinalMeters: 2000)

let request = MKLocalSearch.Request()
request.naturalLanguageQuery = "coffee"
request.region = region

MKLocalSearch(request: request).start { response, error in
guard let destination = response?.mapItems.first else { return }

let request = MKDirections.Request()
request.source = MKMapItem(placemark: MKPlacemark(coordinate: start))
request.destination = destination
MKDirections(request: request).calculate { directionsResponse, _ in
self.route = directionsResponse?.routes.first?.polyline
}
}
}
}

产量:

Coffee

关于mapkit - Swiftui如何使用MKOverlayRenderer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56940371/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com