Search code examples
swiftswift3google-maps-sdk-ios

How do I get the Lat Long of where the user tapped? in Swift v3 and google maps sdk


I'm coding an app in Swift3. I'm using the google maps sdk. I've implemented a GMSMapView. I'm trying to ascertain what lat long that the user tapped in the GMSMapView.

Below is the reference for the android development version of what I think would help. But I can't find the equivalent for iOS.

https://developers.google.com/android/reference/com/google/android/gms/maps/GoogleMap.OnMapClickListener

edit: The "possible duplicate" didn't solve my problem.


Solution

  • I found the solution at: https://developers.google.com/maps/documentation/ios-sdk/events by googling for didTapAtCoordinate, which I somehow knew was part of the SDK.

    The most important line for me was: mapView.delegate = self. It's possible that some other solutions I tried would have worked had I used mapView.delegate = self, but nothing else had mentioned it. Also, the func mapView is of course important so I can use the coordinates of where the user tapped.

    import UIKit
    import GoogleMaps
    
    override func loadView() {
      let camera = GMSCameraPosition.camera(withLatitude: 1.285,
                                            longitude: 103.848,
                                            zoom: 12)
    
      let mapView = GMSMapView.map(withFrame: .zero, camera: camera)
      mapView.delegate = self
      self.view = mapView
    }
    
    // MARK: GMSMapViewDelegate
    class DemoViewController: UIViewController, GMSMapViewDelegate {
    }
    
    func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D) {
            print("You tapped at \(coordinate.latitude), \(coordinate.longitude)")
    }//end func