【问题标题】:iOS Get Location after allow location services permissioniOS 在允许位置服务权限后获取位置
【发布时间】:2015-02-10 23:36:06
【问题描述】:

在应用程序开始时,应用程序对用户当前位置的请求。弹出有关授予应用程序访问位置服务权限的警报框。我的问题是如何在用户允许定位服务后立即获取位置?

我的代码

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.distanceFilter = kCLDistanceFilterNone;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
    [self.locationManager startUpdatingLocation];

    latitude = [NSString stringWithFormat:@"%f",self.locationManager.location.coordinate.latitude];
    longtitude = [NSString stringWithFormat:@"%f",self.locationManager.location.coordinate.longitude];


    GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:[latitude floatValue]
                                                        longitude:[longtitude floatValue]
                                                             zoom:16];
    mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];
    mapView.delegate = self;
    mapView.myLocationEnabled = YES;
    self.view = mapView;

    // Creates a marker in the center of the map.
    GMSMarker *marker = [[GMSMarker alloc] init];
    marker.position = CLLocationCoordinate2DMake([latitude intValue], [longtitude intValue]);
    marker.title = @"Current Location";
    marker.map = mapView;
}

一旦允许定位服务,有没有办法获取用户的当前位置? 我的代码仅在用户允许定位服务然后重新启动应用程序时才有效。

我也尝试实现下面的代码。但是NSLog 没有出现。

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {

    CLLocation *loc = locations.lastObject;
    double speed = loc.speed;
    NSLog(@"speed-----%f ", speed);
}

有什么建议吗?我遗漏了什么吗?

【问题讨论】:

  • 你不见了self.locationManager.delegate=self;
  • 等待...?而已?我会尽快试一试。现在无法尝试。就此事与您联系
  • 是的,iOS 7 及更低版本缺少代理;对于 iOS 8,您需要更多:requestAlwaysAuthorization
  • 是的,你是对的!谢谢
  • @IssacZH。您是否正在从您的代码中获取 currentloaiton?我无法通过此代码获取当前位置

标签: ios google-maps location cllocationmanager


【解决方案1】:

简单地说:

self.locationManager.delegate = self;

在这一行之后:

self.locationManager = [[CLLocationManager alloc] init];

注意: 确保您在头文件中添加了 CLLocationManagerDelegate。

【讨论】:

    【解决方案2】:

    我的答案来得太晚了一年,我正在使用 Swift 2,但对于其他需要答案的人:

    您需要在 didUpdateLocations 委托中更新地图视图。请看下面的代码。

      func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    
      if let location = locations.first {
            mapUIView.camera = GMSCameraPosition(target: location.coordinate, zoom: 15, bearing: 0, viewingAngle: 0)
            locationManager.stopUpdatingLocation()
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-09-17
      • 1970-01-01
      • 2013-02-15
      • 2021-11-24
      • 2013-12-30
      • 2017-09-20
      • 1970-01-01
      • 2017-06-29
      • 2022-11-05
      相关资源
      最近更新 更多