我正在尝试在 iOS 8 的 Swift 项目中使用适用于 iOS 的 Google map 。我添加了 Objective-C 桥接 header 并按照其 documentation 中的说明添加了 Google Maps SDK。 .我试过this示例,一切正常。
我需要显示我当前的位置。我在我的 iOS 8 模拟器中为自定义位置设置了坐标并修改了代码,如 this 中所示。计算器的答案。下面是它的 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 中。我的问题是如何请求 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
}
关于ios - 无法让我的位置显示在 iOS 8 的 Google map 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26192480/