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

Trying to add marker to google map but application gets crash during function call addMarker()

, exception data looks like this,

Application terminated due to uncaught GMSThreadException ", reason:" All calls to the Google Maps iOS SDK must be made from the UI thread "

FYI vwGogleMap is global and in the function I'm trying to plot the 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.

+3


source to share


4 answers


When doing UI updates on the closure (in my case build tokens) remember to get the main thread and do UI operations on the main thread only.

The error is what I have done, I am trying to build markers in the 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 someone!

+16


source


var marker = GMSMarker()
marker.location = location
marker.title = location.name
marker.snippet = "Info window text"
marker.map = mapView

      

The property location

must be set withCLLocationCoordinate2D

To create a new location use this:



 CLLocationCoordinate2D(latitude: CLLocationDegrees(<latitude>), longitude: CLLocationDegrees(<longitude>))

      

It's really simple .. Make sure your map is initialized by doing this

+1


source


    @IBOutlet weak var mapView: GMSMapView!
override func viewDidLoad() {
        super.viewDidLoad()

        mapView.camera = GMSCameraPosition.camera(withLatitude: 18.514043, longitude: 57.377796, zoom: 6.0)
        let marker = GMSMarker(position: CLLocationCoordinate2D(latitude: 18.514043, longitude: 57.377796))
        marker.title = "Lokaci Pvt. Ltd."
        marker.snippet = "Sec 132 Noida India"
        marker.map = mapView
    }

      

0


source


/// Marker - Google Place marker
let marker: GMSMarker = GMSMarker() // Allocating Marker

 marker.title = "Title" // Setting title
 marker.snippet = "Sub title" // Setting sub title
 marker.icon = UIImage(named: "") // Marker icon
 marker.appearAnimation = .pop // Appearing animation. default
 marker.position = location.coordinate // CLLocationCoordinate2D

DispatchQueue.main.async { // Setting marker on mapview in main thread.
   marker.map = mapView // Setting marker on Mapview
}

      

0


source







All Articles