【发布时间】:2014-11-29 07:27:36
【问题描述】:
我正在尝试在适用于 iOS 8 的 Swift 项目中使用适用于 iOS 的 Google Maps。我添加了 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。
我在 info.plist 中添加了 NSLocationWhenInUseUsageDescription 键。我的问题是我如何请求 CLLocationManager 的许可,因为我使用的是 Google Maps SDK。我把下面的代码只是为了检查,但它没有提示权限对话框。
let locationManager = CLLocationManager()
locationManager.requestWhenInUseAuthorization()
有解决办法吗?还是我们必须等到 Google 更新他们的 SDK?
谢谢。
【问题讨论】:
-
你在异步调度中执行什么
self.mapView.myLocationEnabled = true
标签: ios google-maps swift location ios8