Google Maps iOS SDK, Getting Current Location of user

前端 未结 7 2417
渐次进展
渐次进展 2020-12-01 04:49

For my iOS app (building in iOS7),i need to show user\'s current location when the app load.I am using Google Maps iOS SDK. I am follo

7条回答
  •  孤街浪徒
    2020-12-01 05:26

    Xcode + Swift + Google Maps iOS

    Step by step recipe:

    1.) Add key string to Info.plist (open as source code):

    NSLocationWhenInUseUsageDescription
    This app needs your location to function properly
    

    2.) Add CLLocationManagerDelegate to your view controller class:

    class MapViewController: UIViewController, CLLocationManagerDelegate {
       ...
    }
    

    3.) Add CLLocationManager into your class:

    var mLocationManager = CLLocationManager()
    var mDidFindMyLocation = false
    

    4.) Ask for permission and add observer:

    override func viewDidLoad() {
            super.viewDidLoad()          
    
            mLocationManager.delegate = self
            mLocationManager.requestWhenInUseAuthorization()
            yourMapView.addObserver(self, forKeyPath: "myLocation", options: NSKeyValueObservingOptions.new, context: nil)
            ...
    }
    

    5.) Wait for authorization and enable location in Google Maps:

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    
            if (status == CLAuthorizationStatus.authorizedWhenInUse) {
                yourMapView.isMyLocationEnabled = true
            }
    
        }
    

    6.) Add observable for change of location:

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    
            if (!mDidFindMyLocation) {
    
                let myLocation: CLLocation = change![NSKeyValueChangeKey.newKey] as! CLLocation
    
                // do whatever you want here with the location
                yourMapView.camera = GMSCameraPosition.camera(withTarget: myLocation.coordinate, zoom: 10.0)
                yourMapView.settings.myLocationButton = true
    
                mDidFindMyLocation = true
    
                print("found location!")
    
            }
    
        }
    

    That's it!

提交回复
热议问题