一尘不染

无法获取我的位置以显示在iOS 8的Google地图中

swift

我试图在iOS 8的Swift项目中使用iOS版Google Maps。我添加了Objective-
C桥接标头,并按照其文档中的说明添加了Google
Maps SDK
。我尝试了这个示例,一切正常。

我需要显示我的当前位置。我在iOS8模拟器中为自定义位置设置了坐标,并修改了此答案中所示的代码。下面是它的Swift版本。

import UIKit
import Foundation

class MapViewController: UIViewController {

    @IBOutlet var mapView: GMSMapView!

    var firstLocationUpdate: Bool?

    override func viewDidLoad() {
        super.viewDidLoad()

        let camera = GMSCameraPosition.cameraWithLatitude(-33.86, longitude: 151.20, zoom: 12)
        mapView = GMSMapView.mapWithFrame(CGRectZero, camera: camera)
        mapView.settings.compassButton = true
        mapView.settings.myLocationButton = true

        mapView.addObserver(self, forKeyPath: "myLocation", options: .New, context: nil)

        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            self.mapView.myLocationEnabled = true
        })
        println(mapView.myLocation)
        view = mapView

        let marker = GMSMarker()
        marker.position = CLLocationCoordinate2DMake(-33.86, 151.20)
        marker.title = "Sydney"
        marker.snippet = "Australia"
        marker.map = mapView
    }

    override func observeValueForKeyPath(keyPath: String!, ofObject object: AnyObject!, change: [NSObject : AnyObject]!, context: UnsafeMutablePointer<Void>) {
        firstLocationUpdate = true
        let location = change[NSKeyValueChangeNewKey] as CLLocation
        mapView.camera = GMSCameraPosition.cameraWithTarget(location.coordinate, zoom: 14)
    }
}

我运行了它,但是它没有指向我分配的位置。当我println()离开该位置时println(mapView.myLocation),它会返回nil

我认为这是因为在iOS8中,我们必须明确要求用户允许我们获取其位置。

我将NSLocationWhenInUseUsageDescription密钥添加到了info.plist中。我的问题是CLLocationManager由于我使用的是Google
Maps SDK,因此我该如何请求获得许可。我将以下代码用于检查,但未提示权限对话框。

let locationManager = CLLocationManager()
locationManager.requestWhenInUseAuthorization()

有解决方法吗?还是我们必须等到Google更新其SDK?

谢谢。


阅读 290

收藏
2020-07-07

共1个答案

一尘不染

您需要保留CLLocationManager,否则必须先将其释放,然后才有机会显示授权对话框。

class MapViewController: UIViewController {

@IBOutlet var mapView: GMSMapView!

var firstLocationUpdate: Bool?
let locationManager=CLLocationManager()

override func viewDidLoad() {
    super.viewDidLoad()

    self.locationManager.requestWhenInUseAuthorization()

    let camera = GMSCameraPosition.cameraWithLatitude(-33.86, longitude: 151.20, zoom: 12)
    mapView = GMSMapView.mapWithFrame(CGRectZero, camera: camera)
    mapView.settings.compassButton = true
    mapView.settings.myLocationButton = true

    mapView.addObserver(self, forKeyPath: "myLocation", options: .New, context: nil)

    dispatch_async(dispatch_get_main_queue(), { () -> Void in
        self.mapView.myLocationEnabled = true
    })
    println(mapView.myLocation)
    view = mapView

    let marker = GMSMarker()
    marker.position = CLLocationCoordinate2DMake(-33.86, 151.20)
    marker.title = "Sydney"
    marker.snippet = "Australia"
    marker.map = mapView
}
2020-07-07