繁体   English   中英

允许位置服务权限后,iOS获取位置

[英]iOS Get Location after allow location services permission

在应用程序启动时,应用程序请求用户的当前位置。 弹出有关授予应用访问权限服务权限的提示框。 我的问题是用户允许位置服务后如何立即获得位置?

我的密码

- (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;

在此行之后:

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

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

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

您需要在didUpdateLocations委托中更新mapview。 请参见下面的代码。

  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()
    }
}

暂无
暂无

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

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