Home > database >  Detecting a tap on a marker in a forEach Loop and print
Detecting a tap on a marker in a forEach Loop and print

Time:05-10

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
}

CodePudding user response:

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
}

CodePudding user response:

I solved it using this.

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