Search code examples
iosgoogle-mapsswiftgoogle-maps-sdk-ios

Make an API call inside didTapMarker to get the marker title and assign it after response is received in Google Maps API for iOS


I am trying to make an API call inside the didTapMarker function. After the call is done, I am trying to set the marker.title but it does not work. The call is an asynchronous one and I think that somehow related to the problem. Next time I tap the marker it shows the result, but not after the first tap.

Here is the code,

func mapView(mapView: GMSMapView!, didTapMarker marker: GMSMarker!) -> Bool {
    if marker.title == nil{
        makeApiRequest(["id": marker.userData],
            success: {
                (response: Dictionary<String, JSONValue>?) in
                if let name = response?["name"]?.string{
                    marker.title = name
                }
            },
            failure: {
                (error: NSError) in
        })
    }
}

Please help. How should I be doing this to make it work in the first tap.


Solution

  • I think you can use self.mapView (assume self.mapView is your instance variable)

    And do self.mapView .selectedMarker = marker right below marker.title = name

    If your response block still not in the main UI thread, you can update your mapView in the main UI thread

    dispatch_async(dispatch_get_main_queue()) {
        marker.title = name
        self.mapView.selectedMarker = marker
    }