如何在iOS Swift中使用群集解析自定义标记图标

时间:2018-04-02 21:44:25

标签: ios swift google-maps parsing markerclusterer

我有一个模型类,我在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)

}

但它不起作用。它为我带来了谷歌地图的默认标记。我不知道我做错了什么?

2 个答案:

答案 0 :(得分:0)

您正在更改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)

}

答案 1 :(得分:0)

找到解决方案:此处在GMUDefaultClusterRenderer.m中启动聚类文件夹中的类

$image = file_get_contents($_FILES["file"]["tmp_name"]);
$image_name = $_FILES["file"]["name"];

...

我用这个替换原件:

 - (GMSMarker *)markerWithPosition:(CLLocationCoordinate2D)position
                         from:(CLLocationCoordinate2D)from
                     userData:(id)userData
                  clusterIcon:(UIImage *)clusterIcon
                     animated:(BOOL)animated {.....