'Detecting a tap on a marker in a forEach Loop and print

To detect a tap on a marker on GoogleMaps I should use this function.

func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
    print("Do what ever you want.")
    return true
}

This works great. But I show POI dynamically. How can I print the title of the POI which is pressed?

func mapView(_ mapView: GMSMapView, didChange position: GMSCameraPosition) {
    ...
    POIManager.testVariable.forEach {
       let marker1 = GMSMarker()
       marker1.position = CLLocationCoordinate2D(latitude: $0.geometry.location.lat, longitude: $0.geometry.location.lng)
       marker1.title = $0.name
       marker1.map = mapView
       locationManager.stopUpdatingLocation()
    }
    ...
}

I tried it like this but it doesn't work. I guess combining both functions in one is a logical mistake, because of the bool which expects to be true?

func mapView(_ mapView: GMSMapView, didChange position: GMSCameraPosition, didTap marker: GMSMarker) -> Bool {
   ...
    POIManager.testVariable.forEach {
       let marker1 = GMSMarker()
       marker1.position = CLLocationCoordinate2D(latitude: $0.geometry.location.lat, longitude: $0.geometry.location.lng)
       marker1.title = $0.name
       print($0.name)
       marker1.map = mapView
       locationManager.stopUpdatingLocation()
    }
    ...
    return true
}


Solution 1:[1]

You should look into leveraging the GMSMarker userInfo property. You assign this with a dictionary, likely containing an easily referenced property (id) that you can query to get your data.

func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
    let data = marker.userData as? [String:String]
    print(data?["id"]) // get your array object with this id
    return true
}

Solution 2:[2]

I solved it using this.

func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
    print(marker.title)
    return true
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Harry J
Solution 2 submariner