简体   繁体   English

使用iOS版Google Maps API无法获取当前位置坐标

[英]Unable to get current location coordinates using Google Maps API for iOS

I have tried the following code: 我尝试了以下代码:

- (void)viewDidLoad
{
    [super viewDidLoad];
    mapView_.myLocationEnabled = YES;

    CLLocation *myLocation = mapView_.myLocation;
    NSLog(@"%f %f",myLocation.coordinate.latitude, myLocation.coordinate.longitude);
}

The output being logged is 0.000000 0.000000. 正在记录的输出为0.000000 0.000000。

I have also checked in the settings that the location service is enabled and is also showing enabled for my app. 我还检查了设置,启用了位置服务,并且还显示了我的应用已启用。

Please help me figure out where am I going wrong. 请帮助我找出我要去哪里。

It is always show as 0, 0 in the viewDidLoad , you will have to use KVO to observe the coordinate. viewDidLoad ,它始终显示为0,0,您将不得不使用KVO来观察坐标。 Try the following code:- 尝试以下代码:

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.mapView addObserver:self forKeyPath:@"myLocation" options:NSKeyValueObservingOptionNew context: nil];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.mapView removeObserver:self forKeyPath:@"myLocation"];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"myLocation"] && [object isKindOfClass:[GMSMapView class]])
    {
        NSLog(@"KVO triggered. Location Latitude: %f Longitude: %f",self.mapView.myLocation.coordinate.latitude,self.mapView.myLocation.coordinate.longitude);
    }
}

It takes time for the device and the app to work out your location. 设备和应用确定您的位置需要花费时间。 It won't be available on startup. 它在启动时将不可用。 You will need to listen for changes in the location. 您将需要收听位置的更改。

This answer describes how to be notified when myLocation changes: 此答案描述了myLocation更改时如何通知:

https://stackoverflow.com/a/15291319/148241 https://stackoverflow.com/a/15291319/148241

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM