草庐IT

ios - 向具有多个自定义注释 View 的 map View 添加集群注释

coder 2023-09-14 原文

我有一个 map View ,它有两种类型的自定义注释 View 。我想知道如何为这些 View 添加不同类型的集群(取决于注释 View 的类型)。目前,我已尝试按照 WWDC 2017 session 237“MapKit 的新增功能”中的示例项目进行所有操作。但是当我注册我的集群 View 时,它什么都不做(甚至没有被调用)。我想,那是因为我使用自定义注释 View 并且没有注册它们,而是使用 MKMapViewDelegate 方法 mapView(_:viewFor:)。这是我注册自定义集群注释的代码(ClusterView 是我定义集群注释的 MKAnnotationView 的子类):

 mapView.register(ClusterView.self, forAnnotationViewWithReuseIdentifier: MKMapViewDefaultClusterAnnotationViewReuseIdentifier)

上面的代码是在 viewDidLoad() 方法中定义的,但同样,它甚至没有被调用。所以,我认为我应该实现 MKMapViewDelegate 方法之一:mapView(_:clusterAnnotationForMemeberAnnotations:)。问题是,我没有任何添加集群注释的经验,所以我不知道如何正确地实现它。几个星期以来,我一直在 Internet 上寻找一些示例,但还没有找到任何东西(仅关于第三方库)。如果您知道如何实现上述方法,或将集群添加到具有不同类型的自定义注释 View (不使用第三方库)的 mapView 的其他方式,我将非常感谢您的帮助。

最佳答案

尝试使用字符串重用标识符注册您的注释:

mapView.register(AnnotationViewMarker.self, forAnnotationViewWithReuseIdentifier: "marker")
mapView.register(AppleClusterAnnotationView.self, forAnnotationViewWithReuseIdentifier: "cluster")

我也遇到过这个问题。 如果这里有一个适用于我的应用程序的示例:

override func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {        
    if annotation is MKUserLocation || annotation is UserAnnotation {
        return nil
    }

    if let marker = annotation as? WifiAnnotation {
        var view = mapView.dequeueReusableAnnotationView(withIdentifier: "marker") as? AnnotationViewMarker
        if view == nil {
            view = AnnotationViewMarker(annotation: marker, reuseIdentifier: "marker")
        }
        return view

    } else if let cluster = annotation as? MKClusterAnnotation {
        var view = mapView.dequeueReusableAnnotationView(withIdentifier: "cluster") as? AppleClusterAnnotationView
        if view == nil {
            view = AppleClusterAnnotationView(annotation: cluster, reuseIdentifier: "cluster")
        }
        return view

    }

    return nil
}

这里是我的 MKAnnotationView 类的一个例子:

class AppleClusterAnnotationView: MKAnnotationView {
override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
    super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
    displayPriority = .defaultLow
    //collisionMode = .circle
    centerOffset = CGPoint(x: 0, y: -10) // Offset center point to animate better with marker annotations
}

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

override var annotation: MKAnnotation? {
    willSet {
        if let cluster = newValue as? MKClusterAnnotation {
            let renderer = UIGraphicsImageRenderer(size: CGSize(width: 40, height: 40))
            let count = cluster.memberAnnotations.count
            let uniCount = cluster.memberAnnotations.filter { member -> Bool in
                return (member as! WifiAnnotation).wifiType != "Ad"
                }.count
            image = renderer.image { _ in
                // Fill full circle with tricycle color
                UIColor(red: 52/255, green: 131/255, blue: 223/255, alpha: 0.22).setFill()
                UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: 40, height: 40)).fill()

                // Fill pie with unicycle color
                UIColor(red: 52/255, green: 131/255, blue: 223/255, alpha: 0.22).setFill()
                let piePath = UIBezierPath()
                piePath.addArc(withCenter: CGPoint(x: 20, y: 20), radius: 20,
                               startAngle: 0, endAngle: (CGFloat.pi * 2.0 * CGFloat(uniCount)) / CGFloat(count),
                               clockwise: true)
                piePath.addLine(to: CGPoint(x: 20, y: 20))
                piePath.close()
                piePath.fill()

                // Fill inner circle with white color
                UIColor.white.setFill()
                UIBezierPath(ovalIn: CGRect(x: 8, y: 8, width: 24, height: 24)).fill()

                // Finally draw count text vertically and horizontally centered
                let attributes = [ NSAttributedStringKey.foregroundColor: UIColor.black,
                                   NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 15)]
                let text = "\(count)"
                let size = text.size(withAttributes: attributes)
                let rect = CGRect(x: 20 - size.width / 2, y: 20 - size.height / 2, width: size.width, height: size.height)
                text.draw(in: rect, withAttributes: attributes)

            }
        }
    }
}}

最后是我的 MKMarkerAnnotationView。 有了它,您就可以进行所有设置以使其正常工作。您只需设置您的 MKAnnotation。

MKMarkerAnnotationView:

class AnnotationViewMarker: MKMarkerAnnotationView {

override open var annotation: MKAnnotation? {
    willSet {
        if let annotation = newValue as? WifiAnnotation {
            clusteringIdentifier = "WifiAnnotation"

            if annotation.wifiType == "yyy" {
                glyphImage = UIImage(named: "yyy")
                selectedGlyphImage = UIImage(named: "yyy")
                markerTintColor = UIColor("#303030")
                glyphTintColor = .white
                displayPriority = .defaultHigh
                titleVisibility = .visible
                animatesWhenAdded = true


            } else {
                glyphImage = UIImage(named: "xxx")
                selectedGlyphImage = UIImage(named: "xxx")
                markerTintColor = UIColor("#3483DF")
                glyphTintColor = .white
                displayPriority = .required
                titleVisibility = .visible
                animatesWhenAdded = true

                let accessButton = UIButton(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
                accessButton.setImage(self.accessAnnotation, for: .normal) //UIImage(named: "accessAnnotation"), for: .normal)
                rightCalloutAccessoryView = accessButton
            }

            //collisionMode = .circle
        }

    }
}

关于ios - 向具有多个自定义注释 View 的 map View 添加集群注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47251680/

有关ios - 向具有多个自定义注释 View 的 map View 添加集群注释的更多相关文章

  1. ruby - Facter::Util::Uptime:Module 的未定义方法 get_uptime (NoMethodError) - 2

    我正在尝试设置一个puppet节点,但ruby​​gems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由ruby​​gems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby

  2. ruby-on-rails - Rails 3 中的多个路由文件 - 2

    Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题

  3. ruby - 具有身份验证的私有(private) Ruby Gem 服务器 - 2

    我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..

  4. ruby-on-rails - 在 Ruby 中循环遍历多个数组 - 2

    我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代

  5. ruby-on-rails - Rails - 一个 View 中的多个模型 - 2

    我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何

  6. ruby-on-rails - 渲染另一个 Controller 的 View - 2

    我想要做的是有2个不同的Controller,client和test_client。客户端Controller已经构建,我想创建一个test_clientController,我可以使用它来玩弄客户端的UI并根据需要进行调整。我主要是想绕过我在客户端中内置的验证及其对加载数据的管理Controller的依赖。所以我希望test_clientController加载示例数据集,然后呈现客户端Controller的索引View,以便我可以调整客户端UI。就是这样。我在test_clients索引方法中试过这个:classTestClientdefindexrender:template=>

  7. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

  8. ruby-on-rails - form_for 中不在模型中的自定义字段 - 2

    我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢

  9. ruby - 主要 :Object when running build from sublime 的未定义方法 `require_relative' - 2

    我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby​​1.9+ 关于ruby-主要:Objectwhenrun

  10. ruby - 多个属性的 update_column 方法 - 2

    我有一个具有一些属性的模型:attr1、attr2和attr3。我需要在不执行回调和验证的情况下更新此属性。我找到了update_column方法,但我想同时更新三个属性。我需要这样的东西:update_columns({attr1:val1,attr2:val2,attr3:val3})代替update_column(attr1,val1)update_column(attr2,val2)update_column(attr3,val3) 最佳答案 您可以使用update_columns(attr1:val1,attr2:val2

随机推荐