首页 > 系统 > iOS > 正文

iOS开发中最基本的位置功能实现示例

2020-07-26 03:34:09
字体:
来源:转载
供稿:网友

定位获取位置及位置编码-反编码
我们的应用程序,可以通过添加Core Location框架所包含的类,获取设备的地图位置。
添加CoreLocation.framework框架,导入#import<CoreLocation/CoreLocation.h>。
使用地图服务时,会消耗更多地设备电量.因此,在获取到设备的位置后,应该停止定位来节省电量。
我们通过一个demo来展示内容与效果

复制代码 代码如下:

//
// HMTRootViewController.h
// My-GPS-Map
//
// Created by hmt on 14-4-12.
// Copyright (c) 2014年 胡明涛. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface HMTRootViewController : UIViewController <CLLocationManagerDelegate>

@end

//
// HMTRootViewController.m
// My-GPS-Map
//
// Created by hmt on 14-4-12.
// Copyright (c) 2014年 胡明涛. All rights reserved.
//

#import "HMTRootViewController.h"
#import <AddressBook/AddressBook.h>

@interface HMTRootViewController (){

CLLocationManager * _locationManage;
}

@property (nonatomic,retain) CLLocationManager * locationManage;

@end

@implementation HMTRootViewController

- (void)dealloc{

RELEASE_SAFELY(_locationManage);
[super dealloc];

}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.

[self createGPSMap];
self.view.backgroundColor = [UIColor redColor];

}

- (void)createGPSMap{

// 初始化位置服务
self.locationManage = [[CLLocationManager alloc]init];

// 要求CLLocationManager对象返回全部信息
_locationManage.distanceFilter = kCLDistanceFilterNone;

// 设置定位精度
_locationManage.desiredAccuracy = kCLLocationAccuracyBest;

// 设置代理
_locationManage.delegate = self;

// 开始定位
[_locationManage startUpdatingLocation];

[_locationManage release];

}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{

CLLocation * newLocation = [locations lastObject];
// 停止实时定位
[_locationManage stopUpdatingLocation];

// 取得经纬度
CLLocationCoordinate2D coord2D = newLocation.coordinate;
double latitude = coord2D.latitude;
double longitude = coord2D.longitude;
NSLog(@"纬度 = %f 经度 = %f",latitude,longitude);

// 取得精度
CLLocationAccuracy horizontal = newLocation.horizontalAccuracy;
CLLocationAccuracy vertical = newLocation.verticalAccuracy;
NSLog(@"水平方 = %f 垂直方 = %f",horizontal,vertical);

// 取得高度
CLLocationDistance altitude = newLocation.altitude;
NSLog(@"%f",altitude);

// 取得此时时刻
NSDate *timestamp = [newLocation timestamp];
// 实例化一个NSDateFormatter对象
NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];
// 设定时间格式
[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss a"];
[dateFormat setAMSymbol:@"AM"]; // 显示中文, 改成"上午"
[dateFormat setPMSymbol:@"PM"];
// 求出当天的时间字符串,当更改时间格式时,时间字符串也能随之改变
NSString *dateString = [dateFormat stringFromDate:timestamp];
NSLog(@"此时此刻时间 = %@",dateString);


// -----------------------------------------位置反编码--------------------------------------------
CLGeocoder * geocoder = [[CLGeocoder alloc]init];
[geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {

for (CLPlacemark * place in placemarks) {

NSLog(@"name = %@",place.name); // 位置名
NSLog(@"thoroughfare = %@",place.thoroughfare); // 街道
NSLog(@"subAdministrativeArea = %@",place.subAdministrativeArea); // 子街道
NSLog(@"locality = %@",place.locality); // 市
NSLog(@"subLocality = %@",place.subLocality); // 区
NSLog(@"country = %@",place.country); // 国家

NSArray *allKeys = place.addressDictionary.allKeys;
for (NSString *key in allKeys)
{
NSLog(@"key = %@, value = %@",key, place.addressDictionary[key]);
}
#pragma mark - 使用系统定义的字符串直接查询,记得导入AddressBook框架
NSLog(@"kABPersonAddressCityKey = %@", (NSString *)kABPersonAddressCityKey);
NSLog(@"city = %@", place.addressDictionary[(NSString *)kABPersonAddressCityKey]);
NSString *city = place.locality;
if(city == nil)
{
city = place.addressDictionary[(NSString *)kABPersonAddressStateKey];
}
}
}];
}


- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

@end

程序运行结果:(以39.3,116.4为例)

复制代码 代码如下:

//  判断输入的地址 
if (self.locationTextField.text == nil  ||  [self.locationTextField.text length] == 0) { 
    return; 

 
CLGeocoder *geocoder = [[CLGeocoder alloc] init]; 
/*  -----------------------------------------位置编码--------------------------------------------  */ 
[geocoder geocodeAddressString:_locationTextField.text completionHandler:^(NSArray *placemarks, NSError *error) { 
     
    for (CLPlacemark *placemark in placemarks) { 
         
        CLLocationCoordinate2D coordinate = placemark.location.coordinate; 
        NSString *strCoordinate = [NSString stringWithFormat:@"纬度 = %3.5f/n 经度 = %3.5f",coordinate.latitude,coordinate.longitude]; 
        NSLog(@"%@",strCoordinate); 
        NSDictionary *addressDictionary = placemark.addressDictionary; 
        NSString *address = [addressDictionary objectForKey:(NSString *)kABPersonAddressStreetKey]; 
        NSString *state = [addressDictionary objectForKey:(NSString *)kABPersonAddressStateKey]; 
        NSString *city = [addressDictionary objectForKey:(NSString *)kABPersonAddressCityKey]; 
        NSLog(@"街道 = %@/n 省 = %@/n 城市 = %@",address,state,city); 
    } 
}]; 

地图的使用以及标注地图
使用CoreLocation框架获取了当前设备的位置,这一章介绍地图的使用。
首先,导入<MapKit.framework>框架:

复制代码 代码如下:

#import <MapKit/MapKit.h>

main代码示例

复制代码 代码如下:

main.h 
 
#import <UIKit/UIKit.h> 
#import <MapKit/MapKit.h> 
//  引用地图协议 
@interface HMTMainViewController : UIViewController<MKMapViewDelegate> 
 
@end 
 
main.m 
 
// 
//  HMTMainViewController.m 
//  Map 
// 
//  Created by HMT on 14-6-21. 
//  Copyright (c) 2014年 humingtao. All rights reserved. 
// 
 
#import "HMTMainViewController.h" 
#import "HMTAnnotation.h" 
 
@interface HMTMainViewController () 
 
@property (nonatomic ,strong) MKMapView *mapView; 
 
@end 
 
@implementation HMTMainViewController 
 
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
    if (self) { 
        // Custom initialization 
    } 
    return self; 

 
- (void)viewDidLoad 
 

     
    [super viewDidLoad]; 
    self.view.backgroundColor = [UIColor redColor]; 
     
    // Do any additional setup after loading the view. 
     
    self.navigationItem.title = @"地图标注"; 
    self.mapView = [[MKMapView alloc] initWithFrame:CGRectMake(0, 0, 320, 568)]; 
     
    //  是否显示用户当前位置 
    self.mapView.showsUserLocation = YES; 
    //  设置代理 
    self.mapView.delegate = self; 
     
    //  地图显示类型 
    /**
     *      MKMapTypeStandard = 0, //  标准地图
     *      MKMapTypeSatellite,    //  卫星地图
     *      MKMapTypeHybrid        //  混合地图
     */ 
    self.mapView.mapType = MKMapTypeStandard; 
    //  经纬度 
    CLLocationCoordinate2D coord2D = {39.910650,116.47030}; 
    //  显示范围,数值越大,范围就越大 
    MKCoordinateSpan span = {0.1,0.1}; 
    //  显示区域 
    MKCoordinateRegion region = {coord2D,span}; 
    //  给地图设置显示区域 
    [self.mapView setRegion:region animated:YES]; 
    //  是否允许缩放 
    //self.mapView.zoomEnabled = NO; 
    //  是否允许滚动 
    //self.mapView.scrollEnabled = NO; 
 
    //  初始化自定义Annotation(可以设置多个) 
    HMTAnnotation *annotation = [[HMTAnnotation alloc] initWithCGLocation:coord2D]; 
    //  设置标题 
    annotation.title = @"自定义标注位置"; 
    //  设置子标题 
    annotation.subtitle = @"子标题"; 
    //  将标注添加到地图上(执行这步,就会执行下面的代理方法viewForAnnotation) 
    [self.mapView addAnnotation:annotation]; 
     
    [self.view addSubview:_mapView]; 
     

 
//   返回标注视图(大头针视图) 
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{ 
 
    /**
     *  是不是有点像自定义UITableViewCell一样
     */ 
    static NSString *identifier = @"annotation"; 
    //  复用标注视图(MKPinAnnotationView是大头针视图,继承自MKAnnotation) 
    MKPinAnnotationView *annotationView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:identifier]; 
    if (annotationView == nil) { 
        annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifier]; 
    } 
    //  判断是否为自定义的标注视图 
    if ([annotation isKindOfClass:[HMTAnnotation class]]) { 
         
        //  设置大头针圆圈颜色 
        annotationView.pinColor = MKPinAnnotationColorGreen; 
        //  点击头针红色圆圈是否显示上面设置好的标题视图 
        annotationView.canShowCallout = YES; 
        //  要自定义锚点图片,可考虑使用MKAnnotationView;MKPinAnnotationView只能是以大头针形式显示!!!! 
        annotationView.image = [UIImage imageNamed:@"customImage"]; 
        //  添加标题视图右边视图(还有左边视图,具体可自行查看API) 
        UIButton *button = [UIButton buttonWithType:UIButtonTypeDetailDisclosure]; 
        [button addTarget:self action:@selector(didClickAnnotationViewRightButtonAction:) forControlEvents:UIControlEventTouchUpInside]; 
        annotationView.rightCalloutAccessoryView = button; 
        //  是否以动画形式显示标注(从天而降) 
        annotationView.animatesDrop = YES; 
        annotationView.annotation = annotation; 
         
        //  返回自定义的标注视图 
        return annotationView; 
         
    }else{ 
        
        //  当前设备位置的标注视图,返回nil,当前位置会创建一个默认的标注视图 
        return nil; 
    } 
     

 
- (void)didClickAnnotationViewRightButtonAction:(UIButton *)button{ 
 
    NSLog(@"%d %s",__LINE__,__FUNCTION__); 

 
//  更新当前位置调用 
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{ 
 
    NSLog(@"%d %s",__LINE__,__FUNCTION__); 

 
//  选中标注视图 
- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view{ 
     
    NSLog(@"%d %s",__LINE__,__FUNCTION__); 

 
//  地图的现实区域改变了调用 
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated{ 
 
    NSLog(@"%d %s",__LINE__,__FUNCTION__); 

 
- (void)didReceiveMemoryWarning 

    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 

 
@end 

自定义MKAnnotationView

复制代码 代码如下:

#import <Foundation/Foundation.h> 
#import <MapKit/MapKit.h> 
//  引入MKAnnotation协议,切记不能忘记!!!!!!!!! 
@interface HMTAnnotation : NSObject<MKAnnotation> 
 
@property (nonatomic,readonly) CLLocationCoordinate2D coordinate;  //  坐标 
@property (nonatomic,copy) NSString *title;     //  位置名称 
@property (nonatomic,copy) NSString *subtitle;  //  位置子信息(可选) 
 
- (id)initWithCGLocation:(CLLocationCoordinate2D) coordinate; 
 
@end 
 
#import "HMTAnnotation.h" 
 
@implementation HMTAnnotation 
 
- (id)initWithCGLocation:(CLLocationCoordinate2D)coordinate{ 
 
    if (self = [super init]) { 
         
        _coordinate = coordinate; 
    } 
    return self; 

 
@end 

效果图:

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表