简体   繁体   中英

iOS Get Location after allow location services permission

At the start of the application, the application request for user's current location. AlertBox pop up regarding about giving the app permission to access location services. My question is how do I get the location right after the user allows location services?

My Code

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

Is there any way to get user's current location once it allows location services? My codes only works when user allows the location services then restart the app.

I tried implementing the code below as well. But the NSLog is not appearing.

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

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

Any advice? Did I left out anything?

Just put:

self.locationManager.delegate = self;

After this line:

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

Note: Make sure you have added CLLocationManagerDelegate in your header file.

My answer comes a year too late and I'm using Swift 2 but for anyone else requiring an answer:

You need to update the mapview in the didUpdateLocations delegate. Please see the code below.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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