How to add marker for a map view in google maps sdk for ios in swift

Naresh Reddy M picture Naresh Reddy M · Jul 8, 2015 · Viewed 21.8k times · Source

Trying to add a marker to Google map,but the app is getting crashed at while addMarker() function call,Exception details are as follows,

Terminating app due to uncaught exception 'GMSThreadException', reason: 'All calls to the Google Maps SDK for iOS must be made from the UI thread'

FYI vwGogleMap is global and in a function I'm trying to plot marker.

func addMarker() -> Void
{
    var vwGogleMap : GMSMapView?
    var position = CLLocationCoordinate2DMake(17.411647,78.435637)
    var marker = GMSMarker(position: position)
    marker.title = "Hello World"
    marker.map = vwGogleMap
}

Any help would be appreciated,

TIA.

Answer

Naresh Reddy M picture Naresh Reddy M · Jul 8, 2015

When performing UI Updates in closures(In my case - Plotting markers),Do remember to get main thread and perform UI Operations on main thread only.

Mistake what i did is,I'm trying to plot markers in web service completion block.

dispatch_async(dispatch_get_main_queue(),
{
    var position = CLLocationCoordinate2DMake(17.411647,78.435637)
    var marker = GMSMarker(position: position)
    marker.title = "Hello World"
    marker.map = vwGogleMap
})

// For swift 3.0 support.
// 1. Get Main thread
DispatchQueue.main.async
{
    // 2. Perform UI Operations.
    var position = CLLocationCoordinate2DMake(17.411647,78.435637)
    var marker = GMSMarker(position: position)
    marker.title = "Hello World"
    marker.map = vwGoogleMap
}

Hope this helps for someone!