Search code examples
iosgoogle-mapsswift3

GMSMapViewDelegate idleAtCameraPosition is not triggered


I am using the Google Maps SDK for iOS in my app. I need to get the address when map moves. But idleAtCameraPosition is not triggered.

 func vwGMap(vwGMap: GMSMapView!, idleAtCameraPosition position: GMSCameraPosition!) {
        print("changed position: \(vwGMap.camera.target)")  
 }

I have added delegate in viewDidLoad()

vwGMap.delegate = self

and declared the map view

  @IBOutlet var vwGMap: GMSMapView!

Why is idleAtCameraPosition not triggered?

Complete Code

class MapViewController: BaseViewController,CLLocationManagerDelegate, UISearchBarDelegate ,GMSMapViewDelegate, LocateOnTheMap,GMSAutocompleteFetcherDelegate {

    @IBOutlet var marker: UIImageView!

    @IBOutlet var fromaddress: kTextFiledPlaceHolder!

    @IBOutlet var toaddress: kTextFiledPlaceHolder!
    @IBOutlet var fromdummy: kTextFiledPlaceHolder!

    @IBOutlet var vwGMap: GMSMapView!
    var searchResultController: SearchResultsController!
    var resultsArray = [String]()
    var gmsFetcher: GMSAutocompleteFetcher!


    var locationManager = CLLocationManager()
    var didFindMyLocation = false

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.addSlideMenuButton()



        //Location Manager code to fetch current location
        self.locationManager.delegate = self
        self.locationManager.requestWhenInUseAuthorization()

        self.locationManager.startUpdatingLocation()



        vwGMap.delegate = self



         }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)



        searchResultController = SearchResultsController()
        searchResultController.delegate = self
        gmsFetcher = GMSAutocompleteFetcher()
        gmsFetcher.delegate = self

    }







    //Location Manager delegates
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
            let location = locations.last

               let camera = GMSCameraPosition.camera(withLatitude: (location?.coordinate.latitude)!, longitude:(location?.coordinate.longitude)!, zoom:16)
        vwGMap.animate(to: camera)

        CATransaction.begin()
        CATransaction.setValue(5, forKey: kCATransactionAnimationDuration)

        vwGMap.animate(toViewingAngle: 40)
        vwGMap.animate(toBearing: 80)

        //vwGMap.animate(toZoom: 18)

          CATransaction.commit()
        vwGMap.settings.myLocationButton = true
        vwGMap.isMyLocationEnabled = true

        vwGMap.delegate = self
        self.vwGMap.addSubview(toaddress)
        self.vwGMap.addSubview(fromdummy)
        self.vwGMap.addSubview(marker)


        self.locationManager.stopUpdatingLocation()

    }





    public func didFailAutocompleteWithError(_ error: Error) {
        //        resultText?.text = error.localizedDescription
    }

    /**
     * Called when autocomplete predictions are available.
     * @param predictions an array of GMSAutocompletePrediction objects.
     */
    public func didAutocomplete(with predictions: [GMSAutocompletePrediction]) {
        //self.resultsArray.count + 1
        print(predictions)
        for prediction in predictions {

            if let prediction = prediction as GMSAutocompletePrediction!{
                self.resultsArray.append(prediction.attributedFullText.string)
            }
        }
        self.searchResultController.reloadDataWithArray(self.resultsArray)
        //   self.searchResultsTable.reloadDataWithArray(self.resultsArray)
        print("check")
        print(resultsArray)
    }

    func locateWithLongitude(_ lon: Double, andLatitude lat: Double, andTitle title: String) {



        DispatchQueue.main.async { () -> Void in


            let position = CLLocationCoordinate2DMake(lat, lon)
            let marker = GMSMarker(position: position)

            let camera = GMSCameraPosition.camera(withLatitude: lat, longitude: lon, zoom: 10)
//            self.vwGMap.camera = camera
//            
//            marker.title = "Address : \(title)"
//            marker.map = self.vwGMap
            CATransaction.begin()
            CATransaction.setValue(5, forKey: kCATransactionAnimationDuration)
            self.vwGMap.animate(to: camera)

             CATransaction.commit()

        }

    }
    func locate(_ lon: Double, andLatitude lat: Double) {



        DispatchQueue.main.async { () -> Void in



            let camera = GMSCameraPosition.camera(withLatitude: lat, longitude: lon, zoom: 10)
            //            self.vwGMap.camera = camera
            //
            //            marker.title = "Address : \(title)"
            //            marker.map = self.vwGMap
            CATransaction.begin()
            CATransaction.setValue(5, forKey: kCATransactionAnimationDuration)
            self.vwGMap.animate(to: camera)

            CATransaction.commit()

        }

    }

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

        //        let placeClient = GMSPlacesClient()
        //
        //
        //        placeClient.autocompleteQuery(searchText, bounds: nil, filter: nil)  {(results, error: Error?) -> Void in
        //           // NSError myerr = Error;
        //            print("Error @%",Error.self)
        //
        //            self.resultsArray.removeAll()
        //            if results == nil {
        //                return
        //            }
        //
        //            for result in results! {
        //                if let result = result as? GMSAutocompletePrediction {
        //                    self.resultsArray.append(result.attributedFullText.string)
        //                }
        //            }
        //
        //            self.searchResultController.reloadDataWithArray(self.resultsArray)
        //
        //        }

        print(searchText)

        self.resultsArray.removeAll()
        gmsFetcher?.sourceTextHasChanged(searchText)


    }

    func mapView(_ mapView: GMSMapView, idleAtCamera position: GMSCameraPosition) {
        print("changed position")
    }

}

Solution

  • Make sure to extend the class to GMSMapViewDelegate.

    Sample code:

    class Class-name : UIViewController,GMSMapViewDelegate
    

    change code in viewDidLoad:

    vwGMap = GMSMapView()
    vwGMap.delegate = self
    

    Use this method for tap marker event.

    func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D) {
    
    
     print("You tapped at \(coordinate.latitude), \(coordinate.longitude)")
    }
    

    If map view is scroll:

    func mapView(_ mapView: GMSMapView, idleAt cameraPosition: GMSCameraPosition) {
       print("map scrolled.")
    }