objective-cmapkitmkuserlocation

Can't get current user location using MapKit via Objective-C


I'm setting region coordinates here:

// Center Map Here on initial load
#define CENTER_LATITUDE 22.11111  #fake for example
#define CENTER_LONGITUDE -23.99292 #fake for example

I'm setting the region zoom here:

MKCoordinateRegion region;
region.center.latitude = CENTER_LATITUDE;
region.center.longitude = CENTER_LONGITUDE;
region.span.latitudeDelta = SPAN_VALUE;
region.span.longitudeDelta = SPAN_VALUE;
[self.mapView setRegion:region animated:NO];

Here is my mapView didUpdateUserLocation method:

-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation 
  *)userLocation {

  CLLocationCoordinate2D loc = [userLocation coordinate];
  MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(loc, 500, 500);
  [self.mapView setRegion:region animated:YES];

  self.mapView.centerCoordinate = userLocation.location.coordinate;

}

I know this will only zoom in on the defined region, but using something similar to this, is there a way to get the current user location and not a set predefined coordinate like the ones above?

I want the map to find current user location and then zoom to it on the map, if that makes sense.


Solution

  • #import <CoreLocation/CoreLocation.h>
    

    Remember to include the LocationManager delegate within the class file

    @interface YourViewControllerClass ()<CLLocationManagerDelegate>
    
    @property (strong, nonatomic)  CLLocationManager *locationManager;
    
    @end
    

    Set up your locationManager when you are ready to search for the location - from within an IBAction method or even viewDidAppear etc.

    -(void)startUserLocationSearch{
    
         self.locationManager = [[CLLocationManager alloc]init];
         self.locationManager.delegate = self;
         self.locationManager.distanceFilter = kCLDistanceFilterNone;
         self.locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
    
        //Remember your pList needs to be configured to include the location persmission - adding the display message  (NSLocationWhenInUseUsageDescription)
    
         if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
             [self.locationManager requestWhenInUseAuthorization];
         }
         [self.locationManager startUpdatingLocation];
    }
    

    Then this delegate method will fire once the location has been retrieved.

     -(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    
          [self.locationManager stopUpdatingLocation];
          CGFLoat usersLatitude = self.locationManager.location.coordinate.latitude;
          CGFloat usersLongidute = self.locationManager.location.coordinate.longitude;
    
          //Now you have your user's co-oridinates
    }
    

    I hope this helps.