我的 Swift MapKit 注释没有显示
Posted
技术标签:
【中文标题】我的 Swift MapKit 注释没有显示【英文标题】:My Swift MapKit Annotations Aren't Showing 【发布时间】:2020-03-22 18:03:15 【问题描述】:除非我一直放大,否则我的 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!)")
【问题讨论】:
您分享了大量与您的问题无关的代码。我们不需要这些。我们需要查看mapView(_:viewFor:)
和/或您的自定义注释视图类(如果有)。我建议删除所有这些不相关的代码,只显示注释和注释视图相关的代码。
FWIW,听起来您没有正确设置注释视图的displayPriority
和/或您没有正确配置集群。但是在没有任何注释视图相关代码的情况下,任何人都很难帮助你。所以去掉这个不相关的代码,加上注解视图相关的代码……
【参考方案1】:
因此,我建议至少为您的注释(和集群)定义注释视图,设置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 注释没有显示的主要内容,如果未能解决你的问题,请参考以下文章
使用 JSON 文件在 MapKit 中添加 Swift 注释
Swift 2 MapKit Annotations - 如何对注释进行分组?
如何以编程方式在 Mapkit 中选择特定注释 - Swift