ios获取地理位置信息

来源:互联网 发布:centos mount ext4 编辑:程序博客网 时间:2024/04/28 03:35


在程序开发的过程当中,涉及到了获取ios设备所在地址的功能,这个功能非常实用,而且也正好应用到我的练习程序当中。特记录一下具体的实现代码。


locManager =[[ CLLocationManageralloc]init ];

if ([locManagerlocationServicesEnabled]) {

       locManager.delegate =self;

       locManager.desiredAccuracy  =kCLLocationAccuracyBest;

       locManager.distanceFilter  =1000;

       [locManagerstartUpdatingLocation]; 

    }

    else

   {

        NSLog(@"location server error!");

    }


// 两个委托方法,一个是成功获得具体的坐标。另一个是失败的时候的处理方法。


-(void)locationManager:(CLLocationManager*)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation

{

    

    CLLocationCoordinate2D loc = [newLocationcoordinate];

    

    float longtitude = loc.longitude;

    float latitude = loc.latitude;

    

    self.lonLabel.text = [NSStringstringWithFormat:@"%f",longtitude  ];

    

    self.latLabel.text = [NSStringstringWithFormat:@"%f",latitude];

    // 使用CLGeocoder的做法,其实是因为ios5开始,iphone推荐的做法。而MKReverseGeocoder在ios5之后,就不再推荐使用了,因为这个类需要实现两个委托方法。而使用CLGeocodre,则可以使用直接的方法。

    CLGeocoder *geocoder = [[CLGeocoderalloc]init];

    

    [geocoder reverseGeocodeLocation:newLocationcompletionHandler:^(NSArray* placemarks,NSError *error) {

         

         if (placemarks.count >0   ) {

             

             CLPlacemark * plmark = [placemarksobjectAtIndex:0];

             NSString * country = plmark.country;

             NSLog(@"%@",country);

             mycity.text = country;

             

         }

        NSLog(@"%@",placemarks);

    }];

    [geocoder release];

    /*

    MKReverseGeocoder *reverseGeocoder = [[MKReverseGeocoder alloc]initWithCoordinate:loc];

    

    reverseGeocoder.delegate    = self;

    

    [reverseGeocoder start];

    */

}


-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error

{

    NSString * errorMsg = nil;

    if ([error code] ==kCLErrorDenied) {

        errorMsg=@"deny";

    }

    

    if ([errorcode] ==kCLErrorLocationUnknown ) {

        errorMsg = @"fail";

    }

    

    UIAlertView * alertView = [[UIAlertViewalloc]initWithTitle:@"Location"message:errorMsgdelegate:selfcancelButtonTitle:@"OK"otherButtonTitles:nil  ,nil];

    [alertView show];

    [alertView release];

}



这里便非常关键的是,要提供两个头文件和两个framework

#import <CoreLocation/CoreLocation.h>

#import <MapKit/MapKit.h>


mapkit.framework

corelocation.framework