草庐IT

ios11 MKAnnotation 不显示两个注释

coder 2023-09-05 原文

当我将注释添加到 map 时,它们有时会显示,有时不会显示,具体取决于它们彼此之间的距离。如果他们在同一所房子里,可以说一个不会出现。我如何让他们两个都显示?我需要制作自定义注释类吗?我听说 ios11 有一个结 block 功能,我需要使用它吗?这是代码(删节):

import UIKit
import MapKit
import Firebase

class GameViewController: UIViewController {


@IBOutlet weak var mapView: MKMapView!

fileprivate var locations = [CLLocation]()
fileprivate var userLocations = [(loc: CLLocation, name: String, team: String)]()
fileprivate var userAnnotations = [MKAnnotation]()
fileprivate var hasBeenUP = false

var ref: FIRDatabaseReference!
let uid = FIRAuth.auth()!.currentUser!.uid

var timer = Timer()
var timeLeft = 0.0
var firstTimer = Timer()

var name = ""
var team = ""

override func viewDidLoad() {
    super.viewDidLoad()
    let center = CLLocationCoordinate2D(latitude: 47.786769, longitude: -20.413634)
    let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
    self.mapView.setRegion(region, animated: true)
    mapView.mapType = .hybrid
    locationManager.startUpdatingLocation()

    ref = FIRDatabase.database().reference()

    setupULSending()
    getMetaInfo()

    ref.child("realtimeLocations").observe(FIRDataEventType.value, with: { (snapshot) in
        self.userLocations = []
        for rest in snapshot.children.allObjects as! [FIRDataSnapshot] {
            guard let snapshotValue = snapshot.value as? NSDictionary, let snapVal = snapshotValue[rest.key] as? NSDictionary else {
                break
            }
            let name = snapVal["name"] as! String
            let team = snapVal["team"] as? String ?? ""
            if let lat = snapVal["lat"] as? Double,
                let long = snapVal["long"] as? Double {
                let location = CLLocation(latitude: lat, longitude: long)
                self.userLocations.append((loc: location, name: name, team: team))
            }else {

            }
        }
        DispatchQueue.main.async {
            self.updateUserLocation()
        }
    })
}

private lazy var locationManager: CLLocationManager = {
    let manager = CLLocationManager()
    manager.allowsBackgroundLocationUpdates = true
    manager.desiredAccuracy = kCLLocationAccuracyBest
    manager.delegate = self
    manager.requestAlwaysAuthorization()
    return manager
}()

func updateUserLocation() {

    for an in self.mapView.annotations {
        mapView.removeAnnotation(an)
    }
    for loc in userLocations {
        let annotation = MKPointAnnotation()
        annotation.coordinate = loc.loc.coordinate
        annotation.title = loc.name
        annotation.subtitle = "local"
        mapView.addAnnotation(annotation)

    }
}

}

// MARK: - CLLocationManagerDelegate
extension GameViewController: CLLocationManagerDelegate {
  func locationManager(_ manager: CLLocationManager, didUpdateLocations 
  locations: [CLLocation]) {
    let location = locations.last as! CLLocation
    self.locations.append(location)
}
}

最佳答案

在 MKAnnotationView 上,您必须将 MKFeatureDisplayPriority 设置为“必需”。您可以通过实现 MKMapViewDelegate 和 mapView(MKMapView, viewFor: MKAnnotation) 来修改注释 View 。像这样:

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        if annotation is MKUserLocation { return nil }
        var view = mapView.dequeueReusableAnnotationView(withIdentifier: "yourIdentifier")
        if view == nil {
            view = MKMarkerAnnotationView(annotation: nil, reuseIdentifier: "yourIdentifier")
        }
        view?.displayPriority = .required
        return view
}

WWDC 2017 视频 237 中解释了更多选项“MapKit 中的新功能”

关于ios11 MKAnnotation 不显示两个注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47637352/

有关ios11 MKAnnotation 不显示两个注释的更多相关文章

  1. ruby-on-rails - Rails 编辑表单不显示嵌套项 - 2

    我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib

  2. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  3. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  4. ruby-on-rails - 使用 Sublime Text 3 突出显示 HTML 背景语法中的 ERB? - 2

    所以我在关注Railscast,我注意到在html.erb文件中,ruby代码有一个微弱的背景高亮效果,以区别于其他代码HTML文档。我知道Ryan使用TextMate。我正在使用SublimeText3。我怎样才能达到同样的效果?谢谢! 最佳答案 为SublimeText安装ERB包。假设您安装了SublimeText包管理器*,只需点击cmd+shift+P即可获得命令菜单,然后键入installpackage并选择PackageControl:InstallPackage获取包管理器菜单。在该菜单中,键入ERB并在看到包时选择

  5. ruby-on-rails - link_to 不显示任何 rails - 2

    我试图在索引页中创建一个超链接,但它没有显示,也没有给出任何错误。这是我的index.html.erb代码。ListingarticlesTitleTextssss我检查了我的路线,我认为它们也没有问题。PrefixVerbURIPatternController#Actionwelcome_indexGET/welcome/index(.:format)welcome#indexarticlesGET/articles(.:format)articles#indexPOST/articles(.:format)articles#createnew_articleGET/article

  6. ruby-on-rails - 如何在 Rails View 上显示错误消息? - 2

    我是rails的新手,想在form字段上应用验证。myviewsnew.html.erb.....模拟.rbclassSimulation{:in=>1..25,:message=>'Therowmustbebetween1and25'}end模拟Controller.rbclassSimulationsController我想检查模型类中row字段的整数范围,如果不在范围内则返回错误信息。我可以检查上面代码的范围,但无法返回错误消息提前致谢 最佳答案 关键是您使用的是模型表单,一种显示ActiveRecord模型实例属性的表单。c

  7. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  8. Ruby 文件 IO 定界符? - 2

    我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的

  9. ruby - 这两个 Ruby 类初始化定义有什么区别? - 2

    我正在阅读一本关于Ruby的书,作者在编写类初始化定义时使用的形式与他在本书前几节中使用的形式略有不同。它看起来像这样:classTicketattr_accessor:venue,:datedefinitialize(venue,date)self.venue=venueself.date=dateendend在本书的前几节中,它的定义如下:classTicketattr_accessor:venue,:datedefinitialize(venue,date)@venue=venue@date=dateendend在第一个示例中使用setter方法与在第二个示例中使用实例变量之间是

  10. ruby-on-rails - 复数 for fields_for has_many 关联未显示在 View 中 - 2

    目前,Itembelongs_toCompany和has_manyItemVariants。我正在尝试使用嵌套的fields_for通过Item表单添加ItemVariant字段,但是使用:item_variants不显示该表单。只有当我使用单数时才会显示。我检查了我的关联,它们似乎是正确的,这可能与嵌套在公司下的项目有关,还是我遗漏了其他东西?提前致谢。注意:下面的代码片段中省略了不相关的代码。编辑:不知道这是否相关,但我正在使用CanCan进行身份验证。routes.rbresources:companiesdoresources:itemsenditem.rbclassItemi

随机推荐