Search code examples
swiftgoogle-maps-markersgmsmapview

Print UserData for specific key when a marker is tapped


I've added a marker

var marker:  GMSMarker?
let position = CLLocationCoordinate2D(latitude: 38.890106, longitude: -77.007362)
marker = GMSMarker(position: position)
var data = Dictionary<String, Any>()
data["type"] = "Mark1" as String
marker?.userData = data
marker?.map = self.map

Now in func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool { I want to fetch the `["type"] value and for that when I do:

    if marker.userData["type"] == "Mark1" {
        print("It's Marker type 1")
    }

I get error:

Value of type 'Any' has no subscripts

I've search stack overflow with this error above that solution is not related to my problem as it's not related to places.

UPDATE If I simply print: print(marker.userData!) I get:

{
    type = Mark1;
}

But I'm not able to read type in If condition.


Solution

  • Try This

       func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
    
    
        guard let data = marker.userData as? [String:Any] else{return false}
        guard let type = data["type"] as? String else{return false}
        if type == "Mark1"  {
            print("It's Marker type 1")
        }
        return true
    }