Search code examples
iosswiftgoogle-mapsgoogle-maps-sdk-ios

Swift 3 Google Maps iOS SDK - Add Marker via Touch


Hello Everyone!
I have a Google maps in my iOS app, what i'm trying to do is when i tap or longtouch i add a marker in the map and also save the coordinates in an Array
For example: In Android i have the method mMap.setOnLongClickListener() and save those markers in a Latlng Array type

Any help would be useful! Thanks


Solution

  • First you need to add a UILongPressGestureRecognizer to your GMSMapView and implementing the UIGestureDelegate protocol to make it work simultaneously with all gestures of GMSMapView after that in longPress action you should translate the CGPoint of touch and convert it in CLLocationCoordinate2Dthe remain is trivial

    Use this as example

    //
    //  DashedOverlayViewController.swift
    //  GoogleMapsExample
    //
    //  Created by Reinier Melian on 17/07/2017.
    //  Copyright © 2017 Pruebas. All rights reserved.
    //
    
    import UIKit
    import GoogleMaps
    import GooglePlaces
    
    
    
    class DashedOverlayViewController: UIViewController {
    
        @IBOutlet weak var mapView: GMSMapView!
    
        var arrayCoordinates : [CLLocationCoordinate2D] = []
    
        var longPressRecognizer = UILongPressGestureRecognizer()
    
        @IBAction func longPress(_ sender: UILongPressGestureRecognizer) {
            debugPrint("You tapped at YES")
            let newMarker = GMSMarker(position: mapView.projection.coordinate(for: sender.location(in: mapView)))
            self.arrayCoordinates.append(newMarker.position)
            newMarker.map = mapView
        }
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            longPressRecognizer = UILongPressGestureRecognizer(target: self,
                                                               action: #selector(self.longPress))
            longPressRecognizer.minimumPressDuration = 0.5
            longPressRecognizer.delegate = self
            mapView.addGestureRecognizer(longPressRecognizer)
    
            mapView.isMyLocationEnabled = true
            mapView.settings.compassButton = true
    
        }
    
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
    
    
    }
    
    extension DashedOverlayViewController : UIGestureRecognizerDelegate
    {
        public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool
        {
            return true
        }
    }