我的SWIFT MapKit注释未显示

My Swift MapKit Annotations Aren#39;t Showing(我的SWIFT MapKit注释未显示)

本文介绍了我的SWIFT MapKit注释未显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除非我完全放大,否则我的SWIFT MapKit批注不会显示。我不知道为什么,我做了一些研究。

这是我的控制器的代码。

注释确实会显示,但仅当您全程放大时才会显示。当我设置为任何区域和缩放级别时,如何显示它们?

//
//  DeliveryControllerMain.swift
//  CO19
//
//  Created by JJ Zapata on 3/20/20.
//  Copyright © 2020 Jorge Zapata. All rights reserved.
//

import UIKit
import MapKit
import Firebase
import FirebaseCore
import FirebaseAuth
import CoreLocation
import FirebaseDatabase

class DeliveryControllerMain: UIViewController, CLLocationManagerDelegate {

    @IBOutlet var mapView : MKMapView!

    let locationManager = CLLocationManager()

    var posts = [ListObject]()

    override func viewDidLoad() {
        super.viewDidLoad()

        self.checkForLocationservices()
        self.getPlaces()

        // Do any additional setup after loading the view.
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)
        self.getPlaces()
    }

    @IBAction func refrsh(_ sender: UIButton) {
        self.getPlaces()
    }

    func getPlaces() {
        if CheckInternet.Connection() {
            posts.removeAll()

//            let mapAnno = MKPointAnnotation()
//            mapAnno.title = "asdf"
//            mapAnno.coordinate = CLLocationCoordinate2D.init(latitude: 48.314084538662335, longitude: 11.55610970224152)
//            self.mapView.addAnnotation(mapAnno)

//            let allAnnotations = self.mapView.annotations
//            self.mapView.removeAnnotations(allAnnotations)

            let postRef = Database.database().reference().child("Open")

            postRef.observe(.childAdded) { (snapshot) in
                if let value = snapshot.value as? [String : Any] {
                    let user = ListObject()
                    user.id = value["postID"] as? String ?? "Not Found"
                    user.title = value["postTitle"] as? String ?? "Not Found"
                    user.author = value["postAuthor"] as? String ?? "Not Found"
                    user.list = value["postList"] as? String ?? "Not Found"
                    user.date = value["postDate"] as? String ?? "Not Found"
                    user.long = value["postLong"] as? String ?? "Not Found"
                    user.status = value["postStatus"] as? String ?? "Not Found"
                    user.lat = value["postLat"] as? String ?? "Not Found"
                    self.posts.append(user)
                    // MAKE COORDINATES HERE
                    let london = MKPointAnnotation()
                    Database.database().reference().child("Users").child(user.author!).child("name").observe(.value, with: { (data) in
                        let name : String = (data.value as? String)!
                        london.title = name
                        let long = Double(user.long!)
                        let lat = Double(user.lat!)
                        london.coordinate = CLLocationCoordinate2D(latitude: lat!, longitude: long!)
                        self.mapView.addAnnotation(london)
                        print(user.lat!)
                        print(user.long!)
                    })

                }
                print(self.posts.count)
                print(self.posts)
                self.posts.reverse()
                // ACTION HERE
            }
        } else {
            let alert = UIAlertController(title: "No Connection", message: "Please Be Connected To Internet To Access Your LockIt Accounts", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "Okay", style: .default, handler: nil))
            self.present(alert, animated: true, completion: nil)
        }
    }

    func setupLocationanager() {
        self.locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
    }

    func checkAuthoritzation() {
        switch CLLocationManager.authorizationStatus() {
        case .authorizedWhenInUse:
            mapView.showsUserLocation = true
            self.centerViewOnUserLocation()
            break
        case .denied:
            self.makeAlert(title: "Error", message: "Please Check Location Services Settings")
            break
        case .notDetermined:
            locationManager.requestWhenInUseAuthorization()
            break
        case .restricted:
            self.makeAlert(title: "Error", message: "Please Check Location Services Settings")
            break
        case .authorizedAlways:
            mapView.showsUserLocation = true
            break
        default:
            break
        }
    }

    func centerViewOnUserLocation() {
        if let location = locationManager.location?.coordinate {
            let region = MKCoordinateRegion.init(center: location, latitudinalMeters: 1000, longitudinalMeters: 1000)
            mapView.setRegion(region, animated: true)
        }
    }

    func checkForLocationservices() {
        if CLLocationManager.locationServicesEnabled() {
            self.setupLocationanager()
            self.checkAuthoritzation()
        } else {
            self.checkAuthoritzation()
        }
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.last else { return }
        let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
        let region = MKCoordinateRegion.init(center: center, latitudinalMeters: 1, longitudinalMeters: 1)
        mapView.setRegion(region, animated: true)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }

    func makeAlert(title: String, message: String) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Okay", style: .default, handler: nil))
        self.present(alert, animated: true, completion: nil)
    }

    func mapView(mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView) {
        if let annotationTitle = view.annotation?.title {
            print("User tapped on annotation with title: (annotationTitle!)")
        }
    }

}

推荐答案

因此,我建议至少为您的批注(和集群)定义批注视图,设置displayPriority。例如,如果使用MKMarkerAnnotationView

class PointOfInterestClusterAnnotation: MKMarkerAnnotationView {
    override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
        super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
        displayPriority = .required
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override var annotation: MKAnnotation? {
        didSet {
            displayPriority = .required
        }
    }

}

class PointOfInterestAnnotation: MKMarkerAnnotationView {
    static let clusteringIdentifier = "..."

    override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
        super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
        displayPriority = .required
        clusteringIdentifier = PointOfInterestAnnotation.clusteringIdentifier
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override var annotation: MKAnnotation? {
        didSet {
            clusteringIdentifier = PointOfInterestAnnotation.clusteringIdentifier
            displayPriority = .required
        }
    }
}
显然,选择适合您的应用程序的注释名称。但希望这能说明这个想法。

然后在viewDidLoad中注册这两个批注视图:

mapView.register(PointOfInterestAnnotation.self, forAnnotationViewWithReuseIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier)
mapView.register(PointOfInterestClusterAnnotation.self, forAnnotationViewWithReuseIdentifier: MKMapViewDefaultClusterAnnotationViewReuseIdentifier)

(如果面向iOS 11及更高版本,通常需要否mapView(_:viewFor:)。)

如果这样做,缩小时不应该消失注释视图,相反,您应该享受集群的乐趣。当您重新放大时,它们应该会取消聚集并重新显示。

这篇关于我的SWIFT MapKit注释未显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:我的SWIFT MapKit注释未显示

基础教程推荐