Alexey K
Alexey K

Reputation: 6723

Swift - how to add custom fields to markers in Google Maps SDK?

I try to build app with maps, and I want to have additional info in markers. Documentation offers only 2 properties title and snippet. It looks like this

let position = CLLocationCoordinate2DMake(51.5, -0.127)
let london = GMSMarker(position: position)
london.title = "London"
london.snippet = "Population: 8,174,100"
london.map = mapView

For example, I want to add field rating to each marker to display average rating for place.

How can I do that ?

Upvotes: 2

Views: 2981

Answers (1)

Duncan Hoggan
Duncan Hoggan

Reputation: 5100

The Google Maps SDK includes a userData field on the marker object, see link.

Using your example this is what it would look like the following to assign the data.

let mCustomData = customData(starRating: 10)  // init with a rating of 10

let position = CLLocationCoordinate2DMake(51.5, -0.127)
let london = GMSMarker(position: position)
london.title = "London"
london.snippet = "Population: 8,174,100"
london.userData = mCustomData
london.map = mapView

And the customData class something like this.

class customData{
    var starRating: Int
    init(starRating rating: Int) {
        starRating = rating
    }
}

To access the your user data just retrieve it from the marker object.

let mRating = (london.userData as! customData).starRating

Upvotes: 6

Related Questions