如何在 MapKit 中将通用的 Apple 地图图钉用于位置,而不必使用自己的图像作为图钉?



在我的应用程序中,我已经将坐标存储在FireBase中,并在下面的代码中在地图视图上显示这些坐标。还正在利用用户的当前位置。我希望我存储在FireBase中的位置由通用的Apple Maps图钉表示,但我不知道如何让应用程序工作,除非我使用自定义图像作为图钉。此外,地图上显示的表示当前位置的用户的通用"蓝点"不会为我显示。在位置存储在应用内而不是FireBase的不同项目中,通用图钉和蓝点的显示方式与我希望的一样。我该如何解决这个问题?

我尝试过更改代码的零碎部分,但我对 Swift 和整个编程世界相当陌生,找不到解决方案。

class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {

@IBOutlet weak var mapView: MKMapView!

@IBAction func mapSwitch(_ sender: UISwitch) {
if (sender.isOn == true) {
mapView.mapType = MKMapType.standard
}
else {
mapView.mapType = MKMapType.hybrid
}
}

var tappedAnnotation : MKAnnotation?
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

if let view = mapView.dequeueReusableAnnotationView(withIdentifier: "Annotation") {
view.annotation = annotation
view.image = UIImage(named: "pin")
return view
} else {
let view = MKAnnotationView(annotation: annotation, reuseIdentifier: "Annotation")
view.image = UIImage(named: "pin")
view.isEnabled = true
view.canShowCallout = true
view.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
return view
}
}
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
tappedAnnotation = view.annotation
performSegue(withIdentifier: "showAnnotationDetails", sender: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showAnnotationDetails", let dest = segue.destination as? AnnotationDetails {
dest.annotation = tappedAnnotation
}
}

func createAnnotations ( _ annotations : [String:[String:Any]] ) {
mapView.removeAnnotations(mapView.annotations)
for (_,values) in annotations {
if let latDouble = values["latitude"] as? Double, let longDouble = values["longitude"] as? Double {
let lat = CLLocationDegrees( latDouble )
let long = CLLocationDegrees( longDouble )
let coord = CLLocationCoordinate2D(latitude: lat, longitude: long)
let annotation = MKPointAnnotation()
annotation.coordinate = coord
annotation.title = values["name"] as? String ?? ""
annotation.subtitle = values["info"] as? String ?? ""
mapView.addAnnotation(annotation)
}
}
}
let manager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
mapView.delegate = self
mapView.mapType = MKMapType.standard

let ref = Database.database().reference()

ref.child("annotations").observe(.value) { snapshot in 
print(snapshot)
if let annotations = snapshot.value as? [String:[String:Any]] {
self.createAnnotations(annotations)
} else {
print("Data received not formatted as expected")
}
}
}
  • 使用MKPinAnnotationView而不是MKAnnotationView
  • 设置mapView.showsUserLocation = true以显示用户位置(蓝点(

最新更新