1. 导入地图框架,设置代理方法
#import <CoreLocation/CoreLocation.h>
#import<MapKit/MapKit.h>
MKMapViewDelegate,CLLocationManagerDelegate
2. 创建mapView
MKMapView*mapView = [[MKMapView alloc]initWithFrame:CGRectZero];
mapView.mapType=MKMapTypeStandard;
mapView.delegate=self;
[superView addSubview:mapView];
3. 初始化LocationManager
if(nil==_locaManager) {
_locaManager= [[CLLocationManager alloc]init];
}
if([SystemVersion floatValue]>=8.0) {
[_locaManager requestWhenInUseAuthorization];
// [_locaManager requestAlwaysAuthorization];
}
//设置代理
[_locaManager setDelegate:self];
//设置位置的精度
[_locaManager setDesiredAccuracy:kCLLocationAccuracyBest];
//是指多远才更新位置信息设置距离过滤器(多少距离开始更新定位,如下面10米之内就不改变定位)
[_locaManager setDistanceFilter:5.0f];
////授权一直开启定位服务(申请授权;ios8需要加配置;省电考虑;7以前直接调用申请授权的方法)
//[_locaManager requestAlwaysAuthorization];
//还有一种方法requestWhenInUseAuthorization(需要才开启);这两中方法选择时,其在plist中配置的要与之对应
mapView.showsUserLocation=YES;//根据定位的位置标出来(蓝色的圈)
//开启定位服务(开始更新位置信息)
[_locaManager startUpdatingLocation];
//如果不需要实时定位,使用完即使关闭定位服务[myLocationManager stopUpdatingLocation];
4. 代理方法
-(void)locationManager:(CLLocationManager*)manager didUpdateLocations:(NSArray*)locations{
//停止获取位置信息
[self.locaManager stopUpdatingLocation];
//定位关闭
_mapView.showsUserLocation=NO;
//位置信息(NSArray *)locations是一个数组;因为不一定只靠GPS定 位,还可通过基站,WiFi热点等这些辅助来定位
//提示:这里获得的定位信息是地球坐标
//如果不转换成火星坐标那么在苹果原生地图上定位就会有问题
//获取位置对象
CLLocation*lastLocation = [locations lastObject];
//使用第三方库将地球坐标转换成火星坐标
//lastLocation = [lastLocation locationMarsFromEarth];
//取出当前位置的坐标
[self searchLocationDataWithCLLocation:lastLocation];
//提取位置信息里的经度,纬度
CLLocationCoordinate2D myLocation= [lastLocation coordinate];
CLLocationDegrees dinglatitude =myLocation.latitude;
CLLocationDegrees dinglongitude = myLocation.longitude;
}
#pragma mark -搜索城市name
- (void)searchLocationDataWithCLLocation:(CLLocation*)coordinate
{
//ios >=5
CLGeocoder*geocoder = [[CLGeocoder alloc]init];
[geocoder reverseGeocodeLocation:coordinate completionHandler:^(NSArray *_Nullable placemarks,NSError*_Nullable error){
if(placemarks.count>0) {
CLPlacemark*placemark = [placemarks firstObject];
NSString*country = placemark.ISOcountryCode;
NSString*country1 = placemark.country;
NSString*city = placemark.locality;
if(!city) {
//四大直辖市的城市信息无法通过locality获得,只能通过获取省份的方法来获得(如果city为空,则可知为直辖市)
city = placemark.administrativeArea;
}
}else{
}
}];
}