我正在尝试在iOS 8 Swift项目中使用Google Maps for iOS。按照他们的文档说明,我添加了Objective-C桥接头文件并添加了Google Maps SDK。我尝试了这个示例,一切都运作良好。
我需要展示我的当前位置。我在iOS 8模拟器中为自定义位置设置了坐标,并按照这个 StackOverflow 答案中所示修改了代码。下面是它的Swift版本。
我需要展示我的当前位置。我在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(mapView.myLocation)
打印出位置时,它返回nil
。
我认为这是因为在iOS8中,我们必须明确要求用户允许我们获取他们的位置信息。请参见此处。
我已经将NSLocationWhenInUseUsageDescription
键添加到我的info.plist中。我的问题是,由于我正在使用Google Maps SDK,如何请求CLLocationManager
的权限。我只是添加了下面的代码来检查,但它没有弹出权限对话框。
let locationManager = CLLocationManager()
locationManager.requestWhenInUseAuthorization()
有没有解决办法?还是我们必须等待谷歌更新其SDK?
谢谢。
self.mapView.myLocationEnabled = true
是做什么的? - Paulw11