无法让我的位置显示在iOS 8的Google地图中
我正在尝试在iOS 8的Swift项目中使用Google Maps for iOS。我添加了Objective-C桥接标头,并按照其文档中的说明添加了Google Maps SDK。 我试过这个例子,它工作得很好。
我需要显示我目前的位置。 我在我的iOS 8模拟器中设置自定义位置的坐标,并修改了这个 StackOverflow答案中显示的代码。 下面是它的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?
谢谢。
您需要保留您的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 }