swift 如何使用MapKit上的按钮缩放到当前用户位置?

rlcwz9us  于 2023-05-05  发布在  Swift
关注(0)|答案(1)|浏览(149)

我有一个MapView,我想在右上角添加一个按钮,如果按下,缩放到当前用户位置,但我的代码越来越复杂,作为初学者很难知道代码失败的地方
我尝试使用MKUserTrackingButton,它显示按钮,但当我按下它时没有任何React:

struct MapView: UIViewRepresentable {
        let annotations: [CustomAnnotation]
        @Binding var showUserView: Bool
        @Binding var selectedAnnotation: String?
        @State var currentUsername: String

        func makeUIView(context: Context) -> MKMapView {
            let mapView = MKMapView(frame: .zero)
            mapView.delegate = context.coordinator
            mapView.showsUserLocation = true
            mapView.userTrackingMode = .followWithHeading
            mapView.mapType = .hybridFlyover
            let region = MKCoordinateRegion(
                center: CLLocationCoordinate2D(latitude: 0, longitude: 0),
                span: MKCoordinateSpan(latitudeDelta: 180, longitudeDelta: 360))
            mapView.setRegion(region, animated: false)
            mapView.showsBuildings = true
            mapView.addAnnotations(annotations)

            // Add zoom button ------> THIS IS THE RELEVANT CODE
            let zoomButton = MKUserTrackingButton(mapView: mapView)
            let zoomButtonContainer = UIView(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: 40, height: 40)))
            zoomButtonContainer.addSubview(zoomButton)
            zoomButton.translatesAutoresizingMaskIntoConstraints = false
            NSLayoutConstraint.activate([
                zoomButton.bottomAnchor.constraint(equalTo: zoomButtonContainer.bottomAnchor),
                zoomButton.trailingAnchor.constraint(equalTo: zoomButtonContainer.trailingAnchor),
            ])
            mapView.addSubview(zoomButtonContainer)
            zoomButtonContainer.translatesAutoresizingMaskIntoConstraints = false
            NSLayoutConstraint.activate([
                zoomButtonContainer.topAnchor.constraint(equalTo: mapView.safeAreaLayoutGuide.topAnchor, constant: 16),
                zoomButtonContainer.trailingAnchor.constraint(equalTo: mapView.safeAreaLayoutGuide.trailingAnchor, constant: -16),
            ])

            return mapView
        }

        
        
        func updateUIView(_ mapView: MKMapView, context: Context) {
            mapView.removeAnnotations(mapView.annotations)
            mapView.addAnnotations(annotations)
        }
        
        func makeCoordinator() -> Coordinator {
            Coordinator(parent: self)
        }
        
        class Coordinator: NSObject, MKMapViewDelegate {
            let parent: MapView
            
            init(parent: MapView) {
                self.parent = parent
            }
     
            func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
                parent.selectedAnnotation = view.annotation?.title ?? ""
                print("the username is: \(parent.currentUsername)")
                
                if parent.selectedAnnotation == "My Location" {
                    // Do nothing if the selected annotation is the user's location
                    return
                }
                
                if let annotation = view.annotation {
                    mapView.setCenter(annotation.coordinate, animated: true)
                    let span = MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)
                    let region = MKCoordinateRegion(center: annotation.coordinate, span: span)
                    mapView.setRegion(region, animated: true)
                }

                    parent.showUserView.toggle()
                
            }
            
            func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
                guard let customAnnotation = annotation as? CustomAnnotation else {
                    return nil
                }
                
                let annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "customAnnotation")
                annotationView.canShowCallout = true
                annotationView.image = customAnnotation.image
                annotationView.frame.size = CGSize(width: 35, height: 35)
                annotationView.contentMode = .scaleAspectFit
                
                return annotationView
            }

        }
        
    }
}
9avjhtql

9avjhtql1#

要使用按钮缩放到用户在MapKit上的当前位置,可以使用MKMapView类显示Map,使用CLLocationManager类获取用户的当前位置,使用MKCoordinateRegion类设置缩放级别。

@IBOutlet weak var mapView: MKMapView!

 let locationManager = CLLocationManager()

 locationManager.requestWhenInUseAuthorization()
        
        // Set up mapView delegate
        mapView.delegate = self
        
        // Show user's location on the map
        mapView.showsUserLocation = true
        
        // Set up button to zoom to user's location
        let button = UIButton(frame: CGRect(x: 16, y: 100, width: 80, height: 44))
        button.setTitle("Zoom", for: .normal)
        button.addTarget(self, action: #selector(zoomToUserLocation), for: .touchUpInside)
        button.backgroundColor = .white
        button.setTitleColor(.blue, for: .normal)
        button.layer.cornerRadius = 5
        mapView.addSubview(button)


 // Click OF Zoom Button

  func zoomToUserLocation() {

        if let userLocation = mapView.userLocation.location {
            let region = MKCoordinateRegion(center: userLocation.coordinate, latitudinalMeters: 1000, longitudinalMeters: 1000)
            mapView.setRegion(region, animated: true)
        }

    }
    
    // CLLocationManagerDelegate method to update user location
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let location = locations.first {
            print(location.coordinate)
        }
    }

相关问题