Naresh Reddy M Naresh Reddy M - 1 month ago 14
Swift Question

how to add a GMSMarker for a GMSMapView in swift

I'm trying to add a marker to my goglemap object,but the app is getting crashed at initialisation of marker object as

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

here my code is
I've added my map view object Gmap as global at the top of view controller.swift
and in a function I'm trying to add a marker

var Gmap : GMSMapView?

var position = CLLocationCoordinate2DMake(17.411647,78.435637)
var marker = GMSMarker(position: position)
marker.title = "Hello World"
marker.map = Gmap


Thanks in-advance

Answer

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 = Gmap
})

// 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 some