iOS系统地图和定位


大头针类

#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>

@interface MyAnnotation : NSObject<MKAnnotation>

@property(nonatomic, assign) CLLocationCoordinate2D coordinate;

@property(nonatomic, copy) NSString *title;

@property(nonatomic, copy) NSString *subTitle;

-(instancetype)initWithCoordinate:(CLLocationCoordinate2D)coordinate andTitle:(NSString *)title andSubTitle:(NSString *)subTitle;

@end


MyAnnotation.m

#import "MyAnnotation.h"

@implementation MyAnnotation

-(instancetype)initWithCoordinate:(CLLocationCoordinate2D)coordinate andTitle:(NSString *)title andSubTitle:(NSString *)subTitle
{
self = [super init];
if (self) {
_coordinate = coordinate;
_title = title;
_subTitle = subTitle;
}
return self;
}
@end


根视图控制器


//需要引入框架<MapKit/MapKit.h> <CoreLocation/CoreLocation.h>并遵循代理<CLLocationManagerDelegate, MKMapViewDelegate>


#import "ViewController.h"

#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
#import "MyAnnotation.h"

//实现连个代理方法:定位和地图
@interface ViewController ()<CLLocationManagerDelegate, MKMapViewDelegate, UITextFieldDelegate>

@property(nonatomic, strong) CLLocationManager *locationManager; //定位管理器

@property(nonatomic, assign) CLLocationCoordinate2D curLocation; //获取经纬度

@property(nonatomic, strong) MKMapView *mapView; //显示地图

@property(nonatomic, strong) CLLocation *currentLocation;

@property(nonatomic, strong) UITextField *searchTextField;

@property(nonatomic, strong) MyAnnotation *annotation;

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];

#pragma mark 创建地图
[self createMapView];

#pragma mark 定位
// [self getCurPosition];

#pragma mark 创建搜索框
[self createSearch];

}

//创建MapView
-(void)createMapView
{
self.mapView = [[MKMapView alloc] initWithFrame:CGRectMake(0, 65, self.view.frame.size.width, self.view.frame.size.height - 65)];
self.mapView .mapType = MKMapTypeStandard;
self.mapView.zoomEnabled= YES; //可以缩放
self.mapView.showsUserLocation= YES; //打开定位
self.mapView.delegate=self;
self.mapView.userTrackingMode = MKUserTrackingModeFollowWithHeading;
[self.view addSubview:self.mapView];
}

//检测用户位置更新
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
NSLog(@"纬度 :%f, 经度: %f", userLocation.coordinate.latitude, userLocation.coordinate.longitude);
self.currentLocation = userLocation.location;
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(self.currentLocation.coordinate, 1000, 1000);
[self.mapView setRegion:region animated:TRUE];
}

//地图中标记被选中时
-(void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
{
if ([view.annotation isKindOfClass:[MKUserLocation class]]) {

[self getRevGeo];
}
else
{
NSLog(@"===%@", view.annotation);
CLGeocoder *revGeo = [[CLGeocoder alloc]init];
[revGeo reverseGeocodeLocation:self.currentLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
if (!error && [placemarks count] > 0) {
NSDictionary *dict = [[placemarks objectAtIndex:0] addressDictionary];
NSLog(@"%@", [dict allKeys]);
self.annotation.title = [dict objectForKey:@"Name"];
self.annotation.subTitle = [dict objectForKey:@"Name"];
}
else
{
NSLog(@"ERROR: %@", error);
}
}];

}
}

//反地理编码
-(void)getRevGeo
{
CLGeocoder *revGeo = [[CLGeocoder alloc]init];
[revGeo reverseGeocodeLocation:self.currentLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
if (!error && [placemarks count] > 0) {
NSDictionary *dict = [[placemarks objectAtIndex:0] addressDictionary];
// NSLog(@"%@", [dict allKeys]);
// NSLog(@"%@\n %@\n %@\n %@\n %@\n %@\n %@\n %@\n %@\n", [dict objectForKey:@"SubLocality"], [dict objectForKey:@"CountryCode"], [dict objectForKey:@"Street"], [dict objectForKey:@"State"],[dict objectForKey:@"Name"], [dict objectForKey:@"Thoroughfare"],[dict objectForKey:@"FormattedAddressLines"], [dict objectForKey:@"Country"], [dict objectForKey:@"City"]);
//
self.mapView.userLocation.title = [dict objectForKey:@"City"];
self.mapView.userLocation.subtitle = [dict objectForKey:@"Name"];

}
else
{
NSLog(@"ERROR: %@", error);
}
}];
}

-(void)createSearch
{
self.searchTextField = [[UITextField alloc]initWithFrame:CGRectMake(5, 20, self.view.frame.size.width - 70, 40)];
self.searchTextField.placeholder = @"输入查询地点关键字";
self.searchTextField.layer.borderColor = [UIColor lightGrayColor].CGColor;
self.searchTextField.layer.borderWidth = 1;
self.searchTextField.layer.cornerRadius = 5;
self.searchTextField.borderStyle = UITextBorderStyleRoundedRect;
self.searchTextField.delegate = self;
[self.view addSubview:self.searchTextField];

UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeSystem];
searchBtn.frame = CGRectMake(self.searchTextField.frame.size.width + 10, 20, 60, 40);
[searchBtn setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
[searchBtn setTitle:@"查询" forState:UIControlStateNormal];
searchBtn.titleLabel.font = [UIFont systemFontOfSize:20];
[self.view addSubview:searchBtn];
[searchBtn addTarget:self action:@selector(searchAction:) forControlEvents:UIControlEventTouchUpInside];

UIButton *location = [UIButton buttonWithType:UIButtonTypeSystem];
[location setBackgroundImage:[UIImage imageNamed:@"iconfont-dingwei"] forState:UIControlStateNormal];
location.frame = CGRectMake(10, self.view.frame.size.height - 55, 25, 30);
[self.view addSubview:location];
[location addTarget:self action:@selector(locationAction:) forControlEvents:UIControlEventTouchUpInside];
}

//搜索
-(void)searchAction:(UIButton *)btn
{
NSLog(@"%@", self.searchTextField.text);

#pragma mark 地理编码
[self geocoding];
}

//地理编码
-(void)geocoding
{
if (self.searchTextField == nil || self.searchTextField.text.length == 0) {
return;
}
CLGeocoder *geoCode = [[CLGeocoder alloc]init];
[geoCode geocodeAddressString:self.searchTextField.text completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
NSLog(@"查询记录数: %ld", [placemarks count]);
if ([placemarks count] > 0) {
[self.mapView removeAnnotations:self.mapView.annotations];
}
for (int i = 0; i < [placemarks count]; i++) {
CLPlacemark *placeMark = placemarks[i];

[self.searchTextField resignFirstResponder];

//调整地图位置和缩放比例,第一个参数是目标区域的中心点,第二个参数:目标区域南北的跨度,第三个参数:目标区域的东西跨度,单位都是米
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(placeMark.location.coordinate, 3000, 3000);
[self.mapView setRegion:viewRegion animated:YES];

MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(self.currentLocation.coordinate, 1000, 1000);
[self.mapView setRegion:region animated:TRUE];


//实例化MapLocation对象(添加大头针)
self.annotation = [[MyAnnotation alloc]initWithCoordinate:placeMark.location.coordinate andTitle:@"title" andSubTitle:@"subTitle"];
// NSLog(@"%f %f", self.currentLocation.coordinate.latitude, self.currentLocation.coordinate.longitude);
self.mapView.centerCoordinate = placeMark.location.coordinate; //大头针显示在中心位置
[self.mapView selectAnnotation:self.annotation animated:YES];
[self.mapView addAnnotation:self.annotation];
self.currentLocation = placeMark.location;
}
}];
}




//定位
-(void)locationAction:(UIButton *)btn
{
[self mapView:self.mapView didUpdateUserLocation:self.mapView.userLocation];
self.searchTextField.text = @"";
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
[self.searchTextField resignFirstResponder];
return YES;
}



//******************************location定位**********************************

//获取自己的当前的位置信息
-(void)getCurPosition
{
//开始探测自己的位置
if (self.locationManager == nil) {
self.locationManager = [[CLLocationManager alloc]init]; //初始化定位管理器
}

if ([CLLocationManager locationServicesEnabled]) {
self.locationManager.delegate = self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest; //设置最佳精确度
self.locationManager.distanceFilter = 10.0f; //设置当前方位超出10米时, 调用代理方法
[self.locationManager requestWhenInUseAuthorization]; //请求用户授权
[self.locationManager startUpdatingLocation];

// [self.locationManager stopUpdatingLocation]; //关闭对位置的更新
}
}

//错误代理
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(@"error:%@", error);
}

//开启location的权限
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
switch (status) {
case kCLAuthorizationStatusNotDetermined:
if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
[self.locationManager requestAlwaysAuthorization];
}
break;
default:
break;
}
}

//获取当前位置信息(只要位置发生改变,就会调用该方法)
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
self.curLocation = locations.lastObject.coordinate; //保存新位置

//设置显示区域
// MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(locations.lastObject.coordinate, 1000, 1000);
// [self.mapView setRegion:region animated:TRUE];

#pragma mark 显示经纬度
MKCoordinateSpan span = MKCoordinateSpanMake(0.05, 0.05);
MKCoordinateRegion region = MKCoordinateRegionMake(self.curLocation, span);
[self.mapView setRegion:region animated:TRUE];
}

//导航方向发生改变时会调用
-(void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading
{
NSLog(@"导航方向: %@", newHeading);
}

//进入某个区域后调用
-(void)locationManager:(CLLocationManager *)manager didEnterRegion:(nonnull CLRegion *)region
{
NSLog(@"进入某个区域: %@", region);
}

//走出某个区域
-(void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region
{
NSLog(@"走出某个区域: %@", region);
}


- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}

@end


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值