Search code examples
swiftgoogle-mapsgoogle-maps-markersgoogle-maps-sdk-ios

Swift - GoogleMaps SDK get coordinates on touch


I am new to swift and the Google Maps SDK, and was wondering how to get the coordinates of where the user has tapped using the Google Maps SDK. For example if a user holds their finger down on a certain place on a map, a annotation is created there. I would really appreciate your help, thanks.


Solution

  • In the GMSMapViewDelegate there is a method named: mapView:didLongPressAtCoordinate: which is called after a long-press gesture at a particular coordinate. See the reference here.

    By implementing this method you could then add a marker to the map view:

    func mapView(mapView: GMSMapView!, didLongPressAtCoordinate coordinate: CLLocationCoordinate2D) {
         let marker = GMSMarker(position: coordinate)
         marker.title = "Hello World"
         marker.map = mapView
    }
    

    For a tap gesture a similar delegate method can be implemented called mapView:didTapAtCoordinate: which can be used in a similar way:

    func mapView(mapView: GMSMapView!, didTapAtCoordinate coordinate: CLLocationCoordinate2D) {
         print("Tapped at coordinate: " + String(coordinate.latitude) + " " 
                                        + String(coordinate.longitude))
    }