无法通过 Objective-C 使用 MapKit 获取当前用户位置

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

我在这里设置区域坐标:

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

我在这里设置区域缩放:

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

这是我的 mapView didUpdateUserLocation 方法:

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

}

我知道这只会放大定义的区域,但是使用与此类似的东西,有没有办法获取当前用户位置而不是像上面那样设置预定义坐标?

我希望地图找到当前用户位置,然后在地图上放大到它,如果这有意义的话。

#import <CoreLocation/CoreLocation.h>

记得在 class 文件中包含 LocationManager 委托

@interface YourViewControllerClass ()<CLLocationManagerDelegate>

@property (strong, nonatomic)  CLLocationManager *locationManager;

@end

在您准备好搜索位置时设置您的 locationManager - 从 IBAction 方法甚至 viewDidAppear

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

然后,一旦检索到位置,就会触发此委托方法。

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

希望对您有所帮助。

在 didUpdateLocation 方法中添加这两行:

CGFLoat CurrentLatitude = self.locationManager.location.coordinate.latitude;
CGFloat CurrentLongitude = self.locationManager.location.coordinate.longitude;