Search code examples
iosswiftgoogle-mapsparsingmarkerclusterer

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


I have a model class where I parse my item from a JSON file:

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)
}
}

And here, after I fetch the data, I want to bring the marker in the mapView and I want to customize it with an image.

    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)

}

But it doesn't work. It brings me the default marker of google maps. I don't know what I do wrong?


Solution

  • Solution found:Here starts the class in GMUDefaultClusterRenderer.m at clustering folder

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

    ......

    I replace the original with this:

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