我尝试在iOS 8的Swift项目中使用Google Maps for iOS。我添加了Objective-C桥接标头,并按照documentation中的说明添加了Google Maps SDK。我尝试了this示例,它运作良好。
我需要显示我当前的位置。我在iOS 8模拟器中设置了自定义位置的坐标,并修改了代码,如this 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中,我们明确要求用户允许我们获取他们的位置。请参阅here。
我将NSLocationWhenInUseUsageDescription
密钥添加到我的info.plist中。我的问题是,由于我使用的是Google地图SDK,因此如何才能在CLLocationManager
上申请权限。我将以下代码仅用于检查,但它没有提示权限对话框。
let locationManager = CLLocationManager()
locationManager.requestWhenInUseAuthorization()
这有解决方法吗?或者我们是否要等到Google更新他们的SDK?
谢谢。
答案 0 :(得分:7)
您需要保留您的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
}