Swift 3 google map add markers on touch

google-maps, google-maps-markers, swift

Solution

You shouldn't add gesture recognisers manually for Google Maps, it manages it's interactions itself and has dedicated delegate functions to handle common gestures.

To do a long press on a GSMMapView ensure that you set the delegate

self.mapView.delegate = self

and then wire up the appropriate delegate function

extension ViewController: GMSMapViewDelegate {
    func mapView(_ mapView: GMSMapView, didLongPressAt coordinate: CLLocationCoordinate2D) {
         // Custom logic here
         let marker = GMSMarker()
         marker.position = coordinate
         marker.title = "I added this with a long tap"
         marker.snippet = ""
         marker.map = mapView
    }
}

The code above will add a marker at the location you long pressed at, you can also add a title and snippet as you can see. the part that actually adds it to the map is `marker.map = mapView`

Problem

I got problem with google map markers, I want to put marker on touch but I don't know how to handle it I tried a few way but it's not working, nothing happens then I touch on map. It seems something wrong with pressrecognizer. Updated: ``` class MainMapController: UIViewController, CLLocationManagerDelegate { @IBOutlet weak var viewMap: GMSMapView! var makers: [GMSMarker] = [] var locationManager = CLLocationManager() override func viewDidLoad() { super.viewDidLoad() initializeTheLocationManager() self.viewMap.isMyLocationEnabled = true let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress)) self.viewMap.addGestureRecognizer(longPressRecognizer) } func handleLongPress(recognizer: UILongPressGestureRecognizer) { if (recognizer.state == UIGestureRecognizerState.began) { let longPressPoint = recognizer.location(in: self.viewMap); let coordinate = viewMap.projection.coordinate(for: longPressPoint ) let marker = GMSMarker(position: coordinate) marker.opacity = 0.6 marker.title = "Current Location" marker.snippet = "" marker.map = viewMap makers.append(marker) } } func initializeTheLocationManager() { locationManager.delegate = self locationManager.requestWhenInUseAuthorization() locationManager.startUpdatingLocation() } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { var location = locationManager.location?.coordinate cameraMoveToLocation(toLocation: location) locationManager.stopUpdatingLocation() } func cameraMoveToLocation(toLocation: CLLocationCoordinate2D?) { if toLocation != nil { viewMap.camera = GMSCameraPosition.camera(withTarget: toLocation!, zoom: 15) } } ```

Original source