我如何在 iOS Swift 中解析带有聚类的自定义标记图标

How can i parse a custom marker icon with clustering in iOS Swift

我有一个模型 class,我从 JSON 文件解析我的项目:

class Venue: NSObject, GMUClusterItem {

let name: String?
let locationName: String?
let position: CLLocationCoordinate2D
let image = GMSMarker()

init(name: String, locationName: String?, position: CLLocationCoordinate2D, image: GMSMarker)
{
    self.name = name
    self.locationName = locationName
    self.position = position
    //self.image = image

    super.init()
}

var subtitle: String? {
    return locationName
}

class func from(json: JSON) -> Venue?
{
    var name: String
    if let unwrappedTitle = json["name"].string {
        name = unwrappedTitle
    } else {
        name = ""
    }

    let locationName = json["location"]["address"].string
    let lat = json["location"]["lat"].doubleValue
    let long = json["location"]["lng"].doubleValue
    let position = CLLocationCoordinate2D(latitude: lat, longitude: long)
    let image = GMSMarker()

    return Venue(name: name, locationName: locationName, position: position, image: image)
}
}

在这里,在我获取数据之后,我想将标记带入 mapView 中,并且我想使用图像对其进行自定义。

    var venues = [Venue]()
private func generateClusterItems() {


    for venue in venues {

        let name = venue.name
        let position = venue.position
        let locationName = venue.locationName
        let image = GMSMarker()
        let item = Venue(name: name!, locationName: locationName, position: position, image: image)

            let markerView = UIImage(named: "K_Annotation.png")!
            image.icon = markerView

        clusterManager.add(item) 

    }

    clusterManager.cluster()
    clusterManager.setDelegate(self, mapDelegate: self)

}

但是没用。它给我带来了 google 地图的默认标记。我不知道我做错了什么?

您正在更改 image 变量而不是 item.image 变量的图像,因此当您添加项目时,图像永远不会添加到它。

private func generateClusterItems() {


    for venue in venues {

        let name = venue.name
        let position = venue.position
        let locationName = venue.locationName
        let image = GMSMarker()
        let item = Venue(name: name!, locationName: locationName, position: position, image: image)


        let markerView = UIImage(named: "K_Annotation.png")!

        // Change to this
        item.image.icon = markerView

        clusterManager.add(item) 

    }

    clusterManager.cluster()
    clusterManager.setDelegate(self, mapDelegate: self)

}

解决方案 found:Here 在群集文件夹

中启动 GMUDefaultClusterRenderer.m 中的 class
 - (GMSMarker *)markerWithPosition:(CLLocationCoordinate2D)position
                         from:(CLLocationCoordinate2D)from
                     userData:(id)userData
                  clusterIcon:(UIImage *)clusterIcon
                     animated:(BOOL)animated {.....

......

我用这个替换原来的:

  if (clusterIcon != nil) {
marker.icon = clusterIcon;
marker.groundAnchor = CGPointMake(0.5, 0.5);
}else{
marker.icon = [UIImage imageNamed:@"K_Annotation.png"];
}