Current Location in Google Maps with swift

后端 未结 5 953
星月不相逢
星月不相逢 2020-12-17 07:46

I\'m trying to display the user\'s current location on a google map but in the case below, the map doesn\'t even get displayed. What should I change to fix this?



        
5条回答
  •  遥遥无期
    2020-12-17 08:08

    You can try this bellow code its working fine

    import UIKit
    import GoogleMaps
    import GooglePlaces
    
    class SearchMapsViewController: UIViewController,
         UINavigationBarDelegate, GMSAutocompleteFetcherDelegate, 
         LocateOnTheMap, UISearchBarDelegate, CLLocationManagerDelegate 
    {
    
       @IBOutlet var googleMapsContainerView: UIView!
       var searchResultController: SearchResultsController!
       var resultsArray = [String]()
       var googleMapsView:GMSMapView!
       var gmsFetcher: GMSAutocompleteFetcher!
       var locationManager = CLLocationManager()
    
    override func viewDidAppear(animated: Bool) {        
        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.startUpdatingLocation()
    
        self.googleMapsView = GMSMapView (frame: self.googleMapsContainerView.frame)
        self.googleMapsView.settings.compassButton = true
        self.googleMapsView.myLocationEnabled = true
        self.googleMapsView.settings.myLocationButton = true
        self.view.addSubview(self.googleMapsView)
        searchResultController = SearchResultsController()
        searchResultController.delegate = self
        gmsFetcher = GMSAutocompleteFetcher()
        gmsFetcher.delegate = self
    }
    func locationManager(manager: CLLocationManager, didFailWithError error: NSError) 
    {
        print("Error" + error.description)
    }
    
    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) 
    {
        let userLocation = locations.last
        let center = CLLocationCoordinate2D(latitude: userLocation!.coordinate.latitude, longitude: userLocation!.coordinate.longitude)
    
        let camera = GMSCameraPosition.cameraWithLatitude(userLocation!.coordinate.latitude, longitude: userLocation!.coordinate.longitude, zoom: 15);
        self.googleMapsView.camera = camera
        self.googleMapsView.myLocationEnabled = true
    
        let marker = GMSMarker(position: center)
    
        print("Latitude :- \(userLocation!.coordinate.latitude)")
        print("Longitude :-\(userLocation!.coordinate.longitude)")
        marker.map = self.googleMapsView
    
        marker.title = "Current Location"
        locationManager.stopUpdatingLocation()
    }
    

提交回复
热议问题