How to add custom data to marker (Google Maps API SWIFT)

9.8k views Asked by At

I am trying to figure out a way to add custom properties/data for my marker.

What I have used

  • Marker.Title (Store Title)
  • Marker.Snippet (Store object Id)
  • Marker.Icon (Store icon)
  • Marker.userData(to store image)

Additional Information I'd like to store to display on InfoWindow

  • Description(String)

  • A number(Int)

It would be nice if there are more efficient ways of storing and retrieving custom data/properties to display on the infowindow. Any suggestions would be valuable at the moment.

Here is a snippet of what I have at the moment: Setting Marker Data:

 marker.title = object["objectTitle"] as! String
 marker.snippet = objecti.objectId
 marker.icon = UIImage(named:"markerImage")
 marker.userData = UIImage(data:imageData!)

Info Window:

func mapView(mapView: GMSMapView!, markerInfoWindow marker: GMSMarker!) -> UIView! {
    var infoWindow :CustomInfoWindow = NSBundle.mainBundle().loadNibNamed("eventInfo", owner: self, options: nil)[0] as! CustomInfoWindow

    infoWindow.eventTitle.text = marker.title

    infoWindow.Image.image = marker.userData as? UIImage
    marker.userData = UIImage(data:imageData!)
     marker.snippet = object.objectId
    return infoWindow
}
2

There are 2 answers

2
Gamz Rs On BEST ANSWER

I created a struct that has all the data i need and put it in marker.userdata since it supports Any type.

let data = structName(lat: place.lat, long: place.long) // initialize struct
marker.userData = data

Aceess it like this:

let markerLat = (marker.userData as! structName).lat
let markerLong = (marker.userData as! structName).long
4
primehalo On

I came across your question while just starting to learn Swift, but do you think something like this would work:

var myData = Dictionary<String, Any>()
myData["image"] = UIImage(data:imageData!)
myData["description"] = "The description"
myData["number"] = 1
marker.userData = myData

It's a technique to store multiple data types that I just learned about recently.