当前位置未在swift 3中完美显示

时间:2017-12-11 06:22:34

标签: ios swift gps gmsmapview currentlocation

我有一个 GMSMapView ,想要在GMSMapView上显示当前位置。我在 info.plist 源代码中添加了bellow行 -

<key>NSLocationAlwaysUsageDescription</key>
<string>Result</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Result</string>

我的模拟位置是来自xcode的美国加利福尼亚州旧金山。 Simulated location

当我加载GMSMapView时,我会收到位置提醒。 Location Alert

但是当前位置始终显示旧金山和所有地图相关的应用程序在我的iPhone的当前位置变化,这总是旧金山,但现在我的手机位置应显示孟加拉国达卡。 解决方案是什么?
我想通过我的移动GPS获取当前位置。

2 个答案:

答案 0 :(得分:1)

Step 1: Import the this into your controller class 

    import CoreLocation

Step 2: Add this delegate to your class file

    class Your_controller: CLLocationManagerDelegate

Step 3: Declare this above for viewed load

    var locationManager = CLLocationManager()

Step 4: Add this code to your `viewdidload` method

    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestAlwaysAuthorization()
    locationManager.startUpdatingLocation()


    if CLLocationManager.locationServicesEnabled() {
      switch (CLLocationManager.authorizationStatus()) {
        case .notDetermined, .restricted, .denied:
          print("No access")
        case .authorizedAlways, .authorizedWhenInUse:
          print("Access")
      }
    } else {
      print("Location services are not enabled")
    }

Step 5: Add this code below viewdidload method

    func locationManager(_ manager: CLLocationManager,
      didUpdateLocations locations: [CLLocation]) {

      let locationArray = locations as NSArray
      let locationObj = locationArray.lastObject as !CLLocation
      let coord = locationObj.coordinate

      lattitude = coord.latitude
      longitude = coord.longitude
      print(lattitude)
      print(longitude)
    }

Step 6: add to permission your plist file

Key - "Privacy - Location When In Use Usage Description" 

Value - "This app needs access to your location"

Step 7: run your Application on Hardware Device

答案 1 :(得分:0)

viewDidLoad()中的

为位置管理器配置添加以下内容:

override func viewDidLoad() {
    super.viewDidLoad()

    if (CLLocationManager.locationServicesEnabled())
    {
        locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestAlwaysAuthorization()
        locationManager.startUpdatingLocation()
    }
}

进一步实现GMSMapView的代理:

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
    let location = locations.last as CLLocation

    let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)        
    let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))

    self.map.setRegion(region, animated: true)
}