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

时间:2016-01-17 06:41:56

标签: objective-c mapkit mkuserlocation

我在这里设置区域坐标:

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

}

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

我希望地图能够找到当前用户的位置,然后在地图上缩放,如果这是有道理的。

1 个答案:

答案 0 :(得分:1)

@interface YourViewControllerClass ()<CLLocationManagerDelegate>

@property (strong, nonatomic)  CLLocationManager *locationManager;

@end

请记住在类文件中包含LocationManager委托

IBAction

准备好搜索位置时设置您的locationManager - 从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
}

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

// The following sets the appropriate flags to prevent system to go into sleep mode.
SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED | ES_AWAYMODE_REQUIRED);

// This clears the flags and allows the system to sleep normally.
SetThreadExecutionState(ES_CONTINUOUS);

我希望这会有所帮助。