How to “Show my current location on google maps, when I open the ViewController?” in Swift?

后端 未结 7 1560
梦如初夏
梦如初夏 2020-12-14 07:28

I am using Google maps sdk of iOS(Swift).

Has anyone know how to \"Show my current location on google maps, when I open the ViewController\"?

Actually it jus

7条回答
  •  执念已碎
    2020-12-14 07:47

    For Swift 3.x solution, please check this Answer

    First all of you have to enter a key in Info.plist file NSLocationWhenInUseUsageDescription

    After adding this key just make a CLLocationManager variable and do the following

    @IBOutlet weak var mapView: GMSMapView!
    var locationManager = CLLocationManager()
    
    class YourControllerClass: UIViewController,CLLocationManagerDelegate {
    
        //Your map initiation code 
        let mapView = GMSMapView.mapWithFrame(CGRectZero, camera: camera)
        self.view = mapView
        self.mapView?.myLocationEnabled = true
    
        //Location Manager code to fetch current location
        self.locationManager.delegate = self
        self.locationManager.startUpdatingLocation()
    }
    
    
    //Location Manager delegates
    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    
        let location = locations.last
    
        let camera = GMSCameraPosition.cameraWithLatitude((location?.coordinate.latitude)!, longitude: (location?.coordinate.longitude)!, zoom: 17.0)
    
        self.mapView?.animateToCameraPosition(camera)
    
        //Finally stop updating location otherwise it will come again and again in this delegate
        self.locationManager.stopUpdatingLocation()
    
    }
    

    When you run the code you will get a pop up of Allow and Don't Allow for location. Just click on Allow and you will see your current location.

    Make sure to do this on a device rather than simulator. If you are using simulator, you have to choose some custom location and then only you will be able to see the blue dot.

提交回复
热议问题