系统自带定位 可以截取到 国 省 市 区 县 街道 经纬度
#import <CoreLocation/CoreLocation.h>
@interface HomeViewController ()<CLLocationManagerDelegate>
{
CLLocationManager * locationManager;
}
- (void)viewDidLoad {
[super viewDidLoad];
[self locate];
}
- (void)locate{
// 判断定位操作是否被允许
if([CLLocationManager locationServicesEnabled]) {
//定位初始化
if (locationManager == nil) {
locationManager = [[CLLocationManager alloc]init];
}
locationManager.delegate = self;
[locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
if ([[[UIDevice currentDevice]systemVersion]floatValue] >= 8.0) {
[locationManager requestWhenInUseAuthorization];
}
[locationManager startUpdatingLocation];
}else {
//提示用户无法进行定位操作
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"定位不成功 ,请确认开启定位" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
[alertView show];
}
// 开始定位
[locationManager startUpdatingLocation];
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
//此处locations存储了持续更新的位置坐标值,取最后一个值为最新位置,如果不想让其持续更新位置,则在此方法中获取到一个值之后让locationManager stopUpdatingLocation
CLLocation *currentLocation = [locations lastObject];
// 获取当前所在的城市名
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
//根据经纬度反向地理编译出地址信息
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *array, NSError *error)
{
if (array.count > 0)
{
CLPlacemark *placemark = [array objectAtIndex:0];
//NSLog(@%@,placemark.name);//具体位置
//获取城市
NSString *city = placemark.locality;
NSString * neighborhood = placemark.subLocality;
if (!neighborhood) {
if (city) {
neighborhood = city;
}else{
neighborhood = placemark.administrativeArea;
}
}
if (!city) {
//四大直辖市的城市信息无法通过locality获得,只能通过获取省份的方法来获得(如果city为空,则可知为直辖市)
city = placemark.administrativeArea;
}
self.cityName = city;
// NSLog(@"定位完成:%@",self.cityName);
//系统会一直更新数据,直到选择停止更新,因为我们只需要获得一次经纬度即可,所以获取之后就停止更新
[manager stopUpdatingLocation];
[self.leftButton setTitle:self.cityName forState:UIControlStateNormal];
}else if (error == nil && [array count] == 0)
{
// NSLog(@"No results were returned.");
}else if (error != nil)
{
// NSLog(@"An error occurred = %@", error);
}
}];
}
百度地图 定位
#import "MoreMapViewController.h"
#import "GatoReturnButton.h"
#import "GatoBaseHelp.h"
#import "MoreMapTableViewCell.h"
#import <BaiduMapAPI/BMKMapView.h>
#import <BaiduMapAPI/BMKMapComponent.h>
#import <BaiduMapAPI/BMKLocationService.h>
#import <BaiduMapAPI/BMKGeocodeSearch.h>
#import "UIView+Extension.h"
#import <BaiduMapAPI/BMKPoiSearch.h>
//引入周边雷达功能所有的头文件
@interface MoreMapViewController ()<BMKMapViewDelegate,UIGestureRecognizerDelegate,BMKLocationServiceDelegate,BMKGeoCodeSearchDelegate,BMKGeoCodeSearchDelegate>
{
BOOL enableCustomMap;
BMKPinAnnotationView *newAnnotation;
BMKGeoCodeSearch *_geoCodeSearch;
BMKReverseGeoCodeOption *_reverseGeoCodeOption;
BMKMapView *_mapView; //地图
BMKGeoCodeSearch *_geocodesearch; //geo搜索服务
}
@property (nonatomic ,strong) BMKMapView* mapView;
@property (nonatomic ,strong) BMKLocationService * locService;
@property (nonatomic ,strong) UIButton * MyMapButton;
@property (nonatomic ,strong) BMKUserLocation * userLocation;
@property (nonatomic, strong) UISwipeGestureRecognizer *rightSwipeGestureRecognizer;
@property (nonatomic, nonatomic) UIButton *mapPin;
@property (nonatomic ,strong) NSMutableArray * dataArray;
@property (nonatomic ,strong) UITextField * mapTextField;
@end
@implementation MoreMapViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.GatoTableview.frame = CGRectMake(0, 500 * Gato_Height_1334 , Gato_Width, Gato_Height - 500 * Gato_Height_1334);
[self.view addSubview:self.GatoTableview];
self.GatoTableview.backgroundColor = Gato_(240, 240, 240);
GatoReturnButton *returnButton = [[GatoReturnButton alloc] initWithTarget:self IsAccoedingBar:YES];
self.navigationItem.leftBarButtonItem = returnButton;
[self addTheTextField];
[self addBaiDuMap];
[self rightGestuer];
enableCustomMap = YES;
}
-(void)addBaiDuMap
{
//初始化BMKLocationService
self.locService = [[BMKLocationService alloc]init];
self.locService.delegate = self;
//启动LocationService
[self.locService startUserLocationService];
BMKLocationViewDisplayParam* param = [[BMKLocationViewDisplayParam alloc] init];
param.locationViewOffsetY = 0;//偏移量
param.locationViewOffsetX = 0;
param.isAccuracyCircleShow =YES;//设置是否显示定位的那个精度圈
param.isRotateAngleValid = YES;
[_mapView updateLocationViewWithParam:param];
[self.view addSubview:self.mapView];
[self.view addSubview:self.MyMapButton];
}
-(void)rightGestuer
{
self.rightSwipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipes:)];
self.rightSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirectionRight;
[self.view addGestureRecognizer:self.rightSwipeGestureRecognizer];
}
- (void)handleSwipes:(UISwipeGestureRecognizer *)sender
{
if (sender.direction == UISwipeGestureRecognizerDirectionRight) {
NSLog(@"我往右边滑动了一下屏幕");
}
}
-(void)viewWillAppear:(BOOL)animated
{
// [_mapView viewWillAppear];
_mapView.delegate = self; // 此处记得不用的时候需要置nil,否则影响内存的释放
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
// 禁用 iOS7 返回手势
if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
self.navigationController.interactivePopGestureRecognizer.enabled = NO;
self.navigationController.interactivePopGestureRecognizer.delegate = self;
}
}
-(void)viewWillDisappear:(BOOL)animated
{
[super viewDidAppear:animated];
[_mapView viewWillDisappear];
_mapView.delegate = nil; // 不用时,置nil
_geoCodeSearch.delegate = nil; // 不用时,置nil
}
-(void)viewDidDisappear:(BOOL)animated
{
self.navigationController.interactivePopGestureRecognizer.enabled = YES;
}
#pragma mark 地图定位
//实现相关delegate 处理位置信息更新
//处理方向变更信息
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
//NSLog(@"heading is %@",userLocation.heading);
}
//处理位置坐标更新
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
self.userLocation = userLocation;
if (self.userLocation.location.coordinate.latitude > 0) {
if (enableCustomMap == YES) {
[self MyMapButtonDidClicked:nil];
}
}
}
-(void)MyMapButtonDidClicked:(UIButton * )sender
{
[_mapView updateLocationData:self.userLocation];
CLLocationCoordinate2D centerCoor = {self.userLocation.location.coordinate.latitude,self.userLocation.location.coordinate.longitude};
//坐标更新
_mapView.centerCoordinate = centerCoor;
//当前坐标
[_mapView updateLocationData:self.userLocation];
_mapView.showsUserLocation = YES;
// _mapView.centerCoordinate = userLocation.location.coordinate;
// BMKCoordinateRegion region;
// region.center.latitude = userLocation.location.coordinate.latitude;
// region.center.longitude = userLocation.location.coordinate.longitude;
// region.span.latitudeDelta = 0.2;
// region.span.longitudeDelta = 0.2;
if (_mapView)
{
// _mapView.region = region;
NSLog(@"当前的坐标是: %f,%f",self.userLocation.location.coordinate.latitude,self.userLocation.location.coordinate.longitude);
}
if (self.userLocation.location.coordinate.latitude > 0){
enableCustomMap = NO;
self.mapView.frame = CGRectMake(0, 64, Gato_Width, 500 * Gato_Height_1334);
}
}
- (void)changeMapAction:(UISegmentedControl *)segment {
/*
*注:必须在BMKMapView对象初始化之前设置自定义地图样式,设置后会影响所有地图实例
*设置方法:+ (void)customMapStyle:(NSString*) customMapStyleJsonFilePath;
*/
enableCustomMap = segment.selectedSegmentIndex == 1;
}
- (void)mapViewDidFinishLoading:(BMKMapView *)mapView {
// UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"BMKMapView控件初始化完成" delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles: nil];
// [alert show];
// alert = nil;
}
- (void)mapView:(BMKMapView *)mapView onClickedMapBlank:(CLLocationCoordinate2D)coordinate {
NSLog(@"map view: click blank");
}
- (void)mapview:(BMKMapView *)mapView onDoubleClick:(CLLocationCoordinate2D)coordinate {
NSLog(@"map view: double click");
}
- (void)mapView:(BMKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
//屏幕坐标转地图经纬度
CLLocationCoordinate2D MapCoordinate=[_mapView convertPoint:_mapPin.center toCoordinateFromView:_mapView];
NSLog(@"latitude == %f longitude == %f",MapCoordinate.latitude,MapCoordinate.longitude);
if (_geoCodeSearch==nil) {
//初始化地理编码类
_geoCodeSearch = [[BMKGeoCodeSearch alloc]init];
_geoCodeSearch.delegate = self;
}
if (_reverseGeoCodeOption==nil) {
//初始化反地理编码类
_reverseGeoCodeOption= [[BMKReverseGeoCodeOption alloc] init];
}
//需要逆地理编码的坐标位置
_reverseGeoCodeOption.reverseGeoPoint =MapCoordinate;
[_geoCodeSearch reverseGeoCode:_reverseGeoCodeOption];
//创建地理编码对象
CLGeocoder *geocoder=[[CLGeocoder alloc]init];
//创建位置
CLLocation *location=[[CLLocation alloc]initWithLatitude:MapCoordinate.latitude longitude:MapCoordinate.longitude];
//反地理编码
[geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
//判断是否有错误或者placemarks是否为空
if (error !=nil || placemarks.count==0) {
NSLog(@"%@",error);
return ;
}
for (CLPlacemark *placemark in placemarks) {
//赋值详细地址
// NSLog(@"%@",placemark.name);
}
}];
}
//周边信息
- (void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error{
self.dataArray = [NSMutableArray array];
for (BMKPoiInfo *poi in result.poiList) {
// NSLog(@"%@",poi.name);//周边建筑名
// NSLog(@"%d",poi.epoitype);
// NSLog(@"%@",poi.address);
[self.dataArray addObject:poi];
}
// NSArray* array = [NSArray arrayWithArray:_mapView.annotations];
// [_mapView removeAnnotations:array];
// array = [NSArray arrayWithArray:_mapView.overlays];
// [_mapView removeOverlays:array];
// if (error == 0) {
// BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init];
// item.coordinate = result.location;
// item.title = result.address;
// [_mapView addAnnotation:item];
// _mapView.centerCoordinate = result.location;
// NSString* titleStr;
// NSString* showmeg;
// titleStr = @"反向地理编码";
// showmeg = [NSString stringWithFormat:@"%@",item.title];
// UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:titleStr message:showmeg delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定",nil];
// [myAlertView show];
// }
[self.GatoTableview reloadData];
}
-(void)addTheTextField
{
self.navigationController.navigationBar.tintColor = [UIColor clearColor];
self.navigationItem.hidesBackButton = YES;
//self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0.15 green:0.55 blue:0.91 alpha:1];
UIView *naviView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 44)];
naviView.backgroundColor = [UIColor clearColor];
self.mapTextField = [[UITextField alloc] initWithFrame:CGRectMake(- 70 * Gato_Width_750, 25 * Gato_Height_1334, Gato_Width - 200* Gato_Width_750, 24)];
self.mapTextField.returnKeyType = UIReturnKeyDone;
self.mapTextField.borderStyle = UITextBorderStyleRoundedRect;
self.mapTextField.placeholder = @"请输入您的收货地址";
self.mapTextField.font = [UIFont systemFontOfSize:10.0];
self.mapTextField.layer.masksToBounds = YES;
self.mapTextField.layer.cornerRadius = 5;
[self.mapTextField setValue:[UIColor colorWithRed:0.59 green:0.59 blue:0.59 alpha:1] forKeyPath:@"_placeholderLabel.textColor"];
[naviView addSubview:self.mapTextField];
UIButton *BtnRight = [UIButton buttonWithType:UIButtonTypeCustom];
BtnRight.frame = CGRectMake(self.mapTextField.frame.size.width - 26, 4.5, 15, 15);
//[BtnRight addTarget:self action:@selector(onSousuo) forControlEvents:UIControlEventTouchUpInside];
[BtnRight setImage:[UIImage imageNamed:@"icon4"] forState:UIControlStateNormal];
[self.mapTextField addSubview:BtnRight];
UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
rightBtn.frame = CGRectMake(230 * Gato_Width_750, 0, (Gato_Width/2+Gato_Width/5)+20, 44);
rightBtn.backgroundColor = [UIColor clearColor];
[rightBtn addTarget:self action:@selector(touchSearch:) forControlEvents:UIControlEventTouchUpInside];
[naviView addSubview:rightBtn];
self.navigationItem.titleView = naviView;
}
#pragma mark 根据 名字搜索
-(void)touchSearch:(UIButton *)sender
{
_geocodesearch = [[BMKGeoCodeSearch alloc]init];
_geocodesearch.delegate = self; // 此处记得不用的时候需要置nil,否则影响内存的释放
BMKGeoCodeSearchOption *geocodeSearchOption = [[BMKGeoCodeSearchOption alloc]init];
geocodeSearchOption.city= GATO_CITY;
geocodeSearchOption.address = self.mapTextField.text;
BOOL flag = [_geocodesearch geoCode:geocodeSearchOption];
if(flag)
{
NSLog(@"geo检索发送成功");
}
else
{
NSLog(@"geo检索发送失败");
}
}
- (void)onGetGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error {
NSArray* array = [NSArray arrayWithArray:_mapView.annotations];
[_mapView removeAnnotations:array];
array = [NSArray arrayWithArray:_mapView.overlays];
[_mapView removeOverlays:array];
if (error == 0) {
BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init];
item.coordinate = result.location;
item.title = result.address;
[_mapView addAnnotation:item];
_mapView.centerCoordinate = result.location;
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return self.dataArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
MoreMapTableViewCell *cell = [MoreMapTableViewCell cellWithTableView:tableView];
cell.backgroundColor = [UIColor whiteColor];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
if (indexPath.row == 0) {
[cell FirstMapOrOther:YES];
}else{
[cell FirstMapOrOther:NO];
}
BMKPoiInfo *poi = self.dataArray[indexPath.row];
[cell SetValueWithTheName:poi.name WithMap:[NSString stringWithFormat:@"%@ %@",poi.city,poi.address]];
return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 120 * Gato_Height_1334;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
BMKPoiInfo *poi = self.dataArray[indexPath.row];
if (self.MapNameBlock) {
self.MapNameBlock([NSString stringWithFormat:@"%@ %@ %@",poi.city,poi.address,poi.name]);
}
[self.navigationController popViewControllerAnimated:YES];
}
-(BMKMapView *)mapView
{
if (!_mapView) {
_mapView = [[BMKMapView alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
[_mapView setZoomEnabled:YES];
[_mapView setZoomLevel:16];//级别,3-19
_mapView.showMapScaleBar = YES;//比例尺
_mapView.mapScaleBarPosition = CGPointMake(10,_mapView.frame.size.height-45);//比例尺的位置
_mapView.showsUserLocation=YES;//显示当前设备的位置
_mapView.userTrackingMode = BMKUserTrackingModeFollow;//定位跟随模式
[_mapView setMapType:BMKMapTypeStandard];//地图的样式(标准地图)
// self.mapPin = [UIButton buttonWithType:UIButtonTypeSystem];//大头针
// self.mapPin.width = 40;
// self.mapPin.height = 80;
// self.mapPin.center = self.mapView.center;
// [self.mapPin setBackgroundImage:[UIImage imageNamed:@"icon30"] forState:UIControlStateNormal];
// self.mapPin.backgroundColor = [UIColor greenColor];
// [self.mapView addSubview:self.mapPin];
self.MyMapButton = [UIButton buttonWithType:UIButtonTypeCustom];
self.MyMapButton.frame = CGRectMake(30 * Gato_Width_750, 30 * Gato_Height_1334, 33* Gato_Width_750, 33 * Gato_Height_1334);
[self.MyMapButton setImage: [UIImage imageNamed:@"icon30"] forState:UIControlStateNormal];
[self.MyMapButton addTarget:self action:@selector(MyMapButtonDidClicked:) forControlEvents:UIControlEventTouchUpInside];
}
return _mapView;
}
-(NSMutableArray * )dataArray
{
if (!_dataArray) {
_dataArray = [NSMutableArray array];
}
return _dataArray;
}
百度地图效果图
图片.png
网友评论