热门标签 | HotTags
当前位置:  开发笔记 > 开发工具 > 正文

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

这篇文章主要介绍了iOS开发中最基本的位置功能实现示例,需要的朋友可以参考下

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

代码如下:

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

#import

@interface HMTRootViewController : UIViewController

@end

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

#import "HMTRootViewController.h"
#import

@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框架获取了当前设备的位置,这一章介绍地图的使用。
首先,导入框架:

代码如下:

#import

main代码示例

代码如下:

main.h 
 
#import  
#import  
//  引用地图协议 
@interface HMTMainViewController : UIViewController 
 
@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)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  
#import  
//  引入MKAnnotation协议,切记不能忘记!!!!!!!!! 
@interface HMTAnnotation : NSObject 
 
@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 

效果图:


推荐阅读
  • 资源推荐 | TensorFlow官方中文教程助力英语非母语者学习
    来源:机器之心。本文详细介绍了TensorFlow官方提供的中文版教程和指南,帮助开发者更好地理解和应用这一强大的开源机器学习平台。 ... [详细]
  • Explore a common issue encountered when implementing an OAuth 1.0a API, specifically the inability to encode null objects and how to resolve it. ... [详细]
  • 探讨一个显示数字的故障计算器,它支持两种操作:将当前数字乘以2或减去1。本文将详细介绍如何用最少的操作次数将初始值X转换为目标值Y。 ... [详细]
  • 本文详细介绍了Java编程语言中的核心概念和常见面试问题,包括集合类、数据结构、线程处理、Java虚拟机(JVM)、HTTP协议以及Git操作等方面的内容。通过深入分析每个主题,帮助读者更好地理解Java的关键特性和最佳实践。 ... [详细]
  • Android LED 数字字体的应用与实现
    本文介绍了一种适用于 Android 应用的 LED 数字字体(digital font),并详细描述了其在 UI 设计中的应用场景及其实现方法。这种字体常用于视频、广告倒计时等场景,能够增强视觉效果。 ... [详细]
  • RecyclerView初步学习(一)
    RecyclerView初步学习(一)ReCyclerView提供了一种插件式的编程模式,除了提供ViewHolder缓存模式,还可以自定义动画,分割符,布局样式,相比于传统的ListVi ... [详细]
  • 扫描线三巨头 hdu1928hdu 1255  hdu 1542 [POJ 1151]
    学习链接:http:blog.csdn.netlwt36articledetails48908031学习扫描线主要学习的是一种扫描的思想,后期可以求解很 ... [详细]
  • 本文详细介绍了如何在 Spring Boot 应用中通过 @PropertySource 注解读取非默认配置文件,包括配置文件的创建、映射类的设计以及确保 Spring 容器能够正确加载这些配置的方法。 ... [详细]
  • This document outlines the recommended naming conventions for HTML attributes in Fast Components, focusing on readability and consistency with existing standards. ... [详细]
  • 本文详细介绍了Java中org.w3c.dom.Text类的splitText()方法,通过多个代码示例展示了其实际应用。该方法用于将文本节点在指定位置拆分为两个节点,并保持在文档树中。 ... [详细]
  • 本文详细介绍了 Apache Jena 库中的 Txn.executeWrite 方法,通过多个实际代码示例展示了其在不同场景下的应用,帮助开发者更好地理解和使用该方法。 ... [详细]
  • 在现代网络环境中,两台计算机之间的文件传输需求日益增长。传统的FTP和SSH方式虽然有效,但其配置复杂、步骤繁琐,难以满足快速且安全的传输需求。本文将介绍一种基于Go语言开发的新一代文件传输工具——Croc,它不仅简化了操作流程,还提供了强大的加密和跨平台支持。 ... [详细]
  • 题目Link题目学习link1题目学习link2题目学习link3%%%受益匪浅!-----&# ... [详细]
  • 解决微信电脑版无法刷朋友圈问题:使用安卓远程投屏方案
    在工作期间想要浏览微信和朋友圈却不太方便?虽然微信电脑版目前不支持直接刷朋友圈,但通过远程投屏技术,可以轻松实现在电脑上操作安卓设备的功能。 ... [详细]
  • 网络运维工程师负责确保企业IT基础设施的稳定运行,保障业务连续性和数据安全。他们需要具备多种技能,包括搭建和维护网络环境、监控系统性能、处理突发事件等。本文将探讨网络运维工程师的职业前景及其平均薪酬水平。 ... [详细]
author-avatar
huangjia6688_862
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有