我正在尝试使用 Google Maps API,但在获取用户位置时遇到问题。观察到的值似乎永远不会改变,因为observeValueForKeyPath 从未被调用。
注意:我正在运行 Xcode 6-Beta 5 和 iOS 8 beta(代码在 Swift 中)
override func viewDidLoad() {
super.viewDidLoad()
var camera:GMSCameraPosition? = nil
mapView_ = GMSMapView.mapWithFrame(CGRectZero, camera:camera);
mapView_!.addObserver(self, forKeyPath: "myLocation", options: NSKeyValueObservingOptions.fromRaw(0x01)!, context: nil);
camera = GMSCameraPosition.cameraWithTarget(mapView_!.myLocation.coordinate, zoom: 6);
mapView_!.camera = camera;
self.view = mapView_;
dispatch_async(dispatch_get_main_queue(), {
mapView_!.myLocationEnabled = true;
});
}
override func observeValueForKeyPath(keyPath: String!, ofObject object: AnyObject!, change: [NSObject : AnyObject]!, context: UnsafeMutablePointer<()>) {
if (keyPath == "myLocation" && object.isKindOfClass(GMSMapView)) {
mapView_!.animateToCameraPosition(GMSCameraPosition.cameraWithTarget(mapView_!.myLocation.coordinate, zoom: 6));
}
}
截至目前,Google Maps iOS SDK 尚未更新为支持 iOS 8。因此,为了使用位置功能,您需要自行进行 iOS 8 位置授权。
您可以通过实例化来做到这一点CLLocationManager
对象并执行-requestWhenInUseAuthorization
or -requestAlwaysAuthorization
关于这一点。您需要在设置之前执行此操作myLocationEnabled
to YES
.
请务必在您的文件中包含必要的密钥Info.plist
文件。如果您想使用始终授权(如下面的代码示例所示),请提供NSLocationAlwaysUsageDescription
,或者如果您想在使用时授权,NSLocationWhenInUseUsageDescription
。其中之一是必需的,如果您不提供,位置功能将无法工作。
这是 Obj-C 中的示例。抱歉,我还没有掌握所有 Swift 的最新内容。 :)
// Rather than setting -myLocationEnabled to YES directly,
// call this method:
- (void)enableMyLocation
{
CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
if (status == kCLAuthorizationStatusNotDetermined)
[self requestLocationAuthorization];
else if (status == kCLAuthorizationStatusDenied || status == kCLAuthorizationStatusRestricted)
return; // we weren't allowed to show the user's location so don't enable
else
[self.view setMyLocationEnabled:YES];
}
// Ask the CLLocationManager for location authorization,
// and be sure to retain the manager somewhere on the class
- (void)requestLocationAuthorization
{
_locationAuthorizationManager = [[CLLocationManager alloc] init];
_locationAuthorizationManager.delegate = self;
[_locationAuthorizationManager requestAlwaysAuthorization];
}
// Handle the authorization callback. This is usually
// called on a background thread so go back to main.
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
if (status != kCLAuthorizationStatusNotDetermined) {
[self performSelectorOnMainThread:@selector(enableMyLocation) withObject:nil waitUntilDone:[NSThread isMainThread]];
_locationAuthorizationManager.delegate = nil;
_locationAuthorizationManager = nil;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)