您的位置:首页 > 移动开发 > IOS开发

如何在ios设备上定位当前地点,并在地图上显示相关信息

2012-03-13 22:53 459 查看
前几天一个朋友手头发过来一个ios的小项目,其中有关于定位用户当前位置的需求,简单看了下api,写了个定位的demo,在这里作个简单的小结。

首先要做到在地图上显示用户当前位置,我们会用到两个基本的framework,一个是MapKit,还有一个是CoreLocation,前者是用来在界面上呈现mapview,后者主要用户得到用户当前坐标信息后并通知相关委托作一些操作。

在开发前我们首先要在工程.plist文件中加入Required device capabilities一项(如果之前就有了就不要加了,只要添加相关值即可),在这里我们用到的一个值是location-services,顾名思义,位置服务。

做好以上基本操作后我们需要在相关视图中加入我们要显示的mapview,在开发的是时候本人发现,如果是在Ib里面加入mapview,在ib的behavior内就有一个选项叫做shows user location,如果选中的话运行后在mapview刷新后我们即可看到用户当前所在的位置(默认的是一个蓝色头的大头针).

当然了,如果我们需要自定义这个小东西的话也是可以的,我们必须在mapview的委托对象中重写如下方法

- (MKAnnotationView *)mapView:(MKMapView *)theMapView viewForAnnotation:(id <MKAnnotation>)annotation ;
具体的写法我们可以参照ios library中的一个例子,叫做MapCallouts ,个人认为这里例子里面已经写得非常详细了。如果有不明白的直接看这个例子就可以了

要想得到当前用户的坐标其实非常简单,这里我们要实现 CLLocationManagerDelegate 这个协议,并重写
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation 这个方法

CLLocationManager locationManager = [[CLLocationManager alloc] init];
if ([CLLocationManager locationServicesEnabled]) {
NSLog( @"Starting CLLocationManager" );
locationManager.delegate = self;
locationManager.distanceFilter = 200;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
} else {
NSLog( @"Cannot Starting CLLocationManager" );
/*self.locationManager.delegate = self;
self.locationManager.distanceFilter = 200;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[self.locationManager startUpdatingLocation];*/
}


locationManager一旦调用startUpdateLocation方法后成功取得设备的位置,就会调用其委托的 - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation    fromLocation:(CLLocation *)oldLocation 方法,当前用户的位置即newLocation。
我们在取得用户坐标之后即可在mapview中标出用户的具体位置


MKCoordinateSpan theSpan;
//设置地图的范围,越小越精确
theSpan.latitudeDelta = 0.02;
theSpan.longitudeDelta = 0.02;
MKCoordinateRegion theRegion;
theRegion.center = [currentLocation coordinate]; //让地图跳到之前获取到的当前位置checkinLocation
theRegion.span = theSpan;
[mapView setRegion:theRegion]


如果最后要在地图上自定义的MKAnnotation上显示位置的正确名称的话,不要忘了对取得的坐标进行反向解析,这里可以用GOOGLE或其他第三方的的api进行反向解析,反正最后只要能拿到位置的名字就可以了

这里顺便贴一下本人用的一个google的反向解析请求地址,至少目前为止是可以用的

NSString * str = [NSStringstringWithFormat:@"http://ditu.google.cn/maps/geo?hl=zh-CN&output=csv&key=abcdef&q=%f,%f",location.latitude,location.longitude];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: