iOS地理定位

 首先要引入框架CoreLocation.framework和MapKit.framework。

在.h文件中添加

#import <CoreLocation/CoreLocation.h>

#import <MapKit/MapKit.h>

添加代理

@interface ViewController : UIViewController<CLLocationManagerDelegate>

然后,在.m文件中

首先要定义一个locationManager;

@property (strong, nonatomic) CLLocationManager *locationManager;

然后初始化

    self.locationManager = [[CLLocationManager alloc] init];


完了之后就可以开启定位:

    [self.locationManager startUpdatingLocation];

最后调用代理方法完成定位服务:

- (void)locationManager:(CLLocationManager *)manager

    didUpdateToLocation:(CLLocation *)newLocation

           fromLocation:(CLLocation *)oldLocation

{

    

    //将经度显示到label

//    self.longitude.text = [NSString stringWithFormat:@"%lf", newLocation.coordinate.longitude];

    NSLog(@"%lf",newLocation.coordinate.longitude);

    //将纬度现实到label

//    self.latitude.text = [NSString stringWithFormat:@"%lf", newLocation.coordinate.latitude];

    NSLog(@"%lf",newLocation.coordinate.latitude);

    

    

    // 获取当前所在的城市名

    CLGeocoder *geocoder = [[CLGeocoder alloc] init];

    //根据经纬度反向地理编译出地址信息

    [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *array, NSError *error)

     {

         if (array.count > 0)

         {

             CLPlacemark *placemark = [array objectAtIndex:0];

             

             //将获得的所有信息显示到label

//             self.location.text = placemark.name;

             NSLog(@"%@",placemark.name);

             

             //获取城市

             NSString *city = placemark.locality;

             if (!city) {

                 //四大直辖市的城市信息无法通过locality获得,只能通过获取省份的方法来获得(如果city为空,则可知为直辖市)

                 city = placemark.administrativeArea;

             }

             NSLog(@"city = %@", city);

             

         }

         else if (error == nil && [array count] == 0)

         {

             NSLog(@"No results were returned.");

         }

         else if (error != nil)

         {

             NSLog(@"An error occurred = %@", error);

         }

     }];

    

    

    //系统会一直更新数据,直到选择停止更新,因为我们只需要获得一次经纬度即可,所以获取之后就停止更新

    [manager stopUpdatingLocation];

}




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值