我的Swift MapKit注释未显示

问题描述 投票:0回答:1

除非我一直放大,否则我的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!)")
        }
    }

}
ios swift mapkit core-location
1个回答
0
投票

因此,我建议至少为注释(和群集)定义注释视图,并设置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:)

如果执行此操作,则缩小时没有注解视图应该消失,而是应该享受聚类。当您放大时,它们应该会消失并重新出现。

© www.soinside.com 2019 - 2024. All rights reserved.