如何在mkmapview中查找用户的当前位置

时间:2013-11-20 07:43:26

标签: ios objective-c mkmapview cllocationmanager

我想找到用户的当前位置 在代码下面,用于从定义良好的地址中查找坐标  我可以找到用户的当前位置..请帮助我

.h文件     #进口     #进口

@interface ViewController : UIViewController<MKMapViewDelegate,CLLocationManagerDelegate>
@property(nonatomic,retain)  MKMapView *myMapView;
@property (nonatomic, strong) CLGeocoder *myGeocoder;
@end

.m文件

#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>

@interface ViewController ()
{
    CLLocationManager *locationManager;
}

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];


    self.myMapView.showsUserLocation=YES;

    self.view.backgroundColor=[UIColor whiteColor];
    self.myMapView=[[MKMapView alloc]initWithFrame:self.view.bounds];

    self.myMapView.mapType=MKMapTypeHybrid;
    self.myMapView.autoresizingMask=UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:self.myMapView];


    locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate=self;
    locationManager.desiredAccuracy=kCLLocationAccuracyBest;
    locationManager.distanceFilter=kCLDistanceFilterNone;

    [locationManager startUpdatingLocation];

   NSString *oreillyAddress =@"india";
  self.myGeocoder = [[CLGeocoder alloc] init];
    [self.myGeocoder
     geocodeAddressString:oreillyAddress completionHandler:^(NSArray *placemarks, NSError *error)
   {
        if ([placemarks count] > 0 && error == nil)
            {
       NSLog(@"Found %lu placemark(s).", (unsigned long)[placemarks count]);
             CLPlacemark *firstPlacemark = [placemarks objectAtIndex:0]; NSLog(@"Longitude = %f", firstPlacemark.location.coordinate.longitude); NSLog(@"Latitude = %f", firstPlacemark.location.coordinate.latitude);


         }
         else if ([placemarks count] == 0 &&
                  error == nil){ NSLog(@"Found no placemarks.");
        }
         else if (error != nil){
             NSLog(@"An error occurred = %@", error); }
     }];


    // Do any additional setup after loading the view, typically from a nib.
}
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    return YES;
}
- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{
    float latitude=newLocation.coordinate.latitude;
    float longitude=newLocation.coordinate.longitude;
    NSLog(@"%f",latitude);
    NSLog(@"%f",longitude);
    [locationManager stopUpdatingLocation];

}

- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error
{
    NSLog(@"error==>%@",error);
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

5 个答案:

答案 0 :(得分:4)

定义

CLLocationManager * lm;

CLLocation * location;

然后在ViewDidLoad方法中添加下面提到的代码

lm = [[CLLocationManager alloc] init];
    lm.delegate = self;
    lm.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
    lm.distanceFilter = kCLDistanceFilterNone;
    [lm startUpdatingLocation];

    location = [lm location];

    CLLocationCoordinate2D coordinate;
    coordinate.longitude = location.coordinate.longitude;
    coordinate.latitude = location.coordinate.latitude;


    if((location.coordinate.longitude== 0.0 ) && (location.coordinate.latitude==0.0))
    {
        UIAlertView *alert2 = [[UIAlertView alloc ] initWithTitle:(@"Server Error:")message:(@"Internet Problem. Try Later !!!") delegate:nil cancelButtonTitle:nil otherButtonTitles:(@"OK"), nil];
        [alert2 show];

    }

    else
    {


        coordinate = [location coordinate];

        NSLog(@"Latitude of User is %f",coordinate.longitude);
        NSLog(@"Longitude of User is %f",coordinate.latitude);
        }

答案 1 :(得分:2)

使用此

self.myMapView.showsUserLocation = YES;

答案 2 :(得分:0)

如果您使用的是模拟器,则需要转到:Debug - &gt;位置 - &gt;顾客。从那里将您的位置设置为所需的测试点。

答案 3 :(得分:0)

获取用户在iOS 8中的当前位置

  1. 在.h文件中添加<CLLocationManagerDelegate>
  2. CLLocationManager *locationManager; CLLocation *currentLocation;

  3. locationManager = [CLLocationManager new];
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0 && [CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedWhenInUse)
    {
    [locationManager requestAlwaysAuthorization];
    }
    
    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    locationManager.distanceFilter = kCLDistanceFilterNone;
    [locationManager startUpdatingLocation];
    
    
    
    - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    CLLocation *location = [locations lastObject];
    NSLog(@"lat%f - lon%f", location.coordinate.latitude, location.coordinate.longitude);
    
    NSString *currentLatitude = [NSString stringWithFormat:@"%f",location.coordinate.latitude];
    NSString *currentLongitude = [NSString stringWithFormat:@"%f",location.coordinate.longitude];
    
    [locationManager stopUpdatingLocation];
    }
    
    -(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
     {
    switch (status)
    {
    case kCLAuthorizationStatusNotDetermined:
    case kCLAuthorizationStatusRestricted:
    case kCLAuthorizationStatusDenied:
    {
        [locationManager requestAlwaysAuthorization];
    }
        break;
    default:
    {
        [locationManager startUpdatingLocation];
    }
        break;
    }
    }
    
         - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
         {
             NSLog(@"Error while getting core location : %@",[error localizedFailureReason]);
               if ([error code] == kCLErrorDenied)
          {
             //you had denied
          }
             [manager stopUpdatingLocation];
         }
    
  4. 在你的plist文件中别忘了输入密钥

    NSLocationAlwaysUsageDescription
    

答案 4 :(得分:0)

使用此:

[self.mapview setShowsUserLocation:YES];