我有一个 MapView,我想在右上角添加一个按钮,如果按下该按钮,则会缩放到当前用户位置,但是我的代码越来越复杂,作为初学者很难知道代码在哪里失败
我尝试使用 MKUserTrackingButton,它显示了按钮,但当我按下它时没有任何反应:
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
}
}
}
}
要使用按钮缩放到 MapKit 上用户的当前位置,您可以使用 MKMapView 类来显示地图,使用 CLLocationManager 类来获取用户的当前位置,并使用 MKCoordinateRegion 类来设置缩放级别。
@IBOutlet 弱变量 mapView:MKMapView!
让 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)
// 点击缩放按钮
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)
}
}