废话不说,直接上代码
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
@interface PositionController ()<CLLocationManagerDelegate,MKMapViewDelegate>
{
//添加代理协议 CLLocationManagerDelegate
CLLocationManager *_locationManager;//定位服务管理类
}
@property (nonatomic, strong)NSString *position;//现在位置
@property (nonatomic, assign)CLLocationCoordinate2D Coordinate2D;//现在的坐标
@property (nonatomic, assign)CLLocationCoordinate2D address;//目的地坐标
@property (nonatomic, strong)NSString *addressName;//目的地名字
@property (nonatomic, strong)MKMapView *mapView;//地图
- (MKMapView *)mapView{
if (!_mapView) {
_mapView = [[MKMapView alloc] initWithFrame:CGRectMake(self.space, self.gotoBtn.bottom+self.space, WIDTH-2*self.space, HEIGHT-self.gotoBtn.bottom-2*self.space-64)];
_mapView.backgroundColor=[[UIColor redColor] colorWithAlphaComponent:0.2];
/**
MKMapTypeStandard = 0, // 标准
MKMapTypeSatellite, // 卫星
MKMapTypeHybrid, // 混合(标准+卫星)
MKMapTypeSatelliteFlyover NS_ENUM_AVAILABLE(10_11, 9_0), // 3D立体卫星
MKMapTypeHybridFlyover NS_ENUM_AVAILABLE(10_11, 9_0), // 3D立体混合
*/
_mapView.mapType = MKMapTypeStandard;//地图显示类型
_mapView.userTrackingMode=MKUserTrackingModeFollow;//添加此句,可以自动定位到当前位置
_mapView.delegate=self;
_mapView.showsScale = YES;
// 是否可以缩放
_mapView.zoomEnabled = YES;
// 是否可以滚动
_mapView.scrollEnabled = YES;
// 是否可以旋转
_mapView.rotateEnabled = YES;
// 是否显示3D
_mapView.pitchEnabled = YES;
}
return _mapView;
}
- (void)viewDidLoad {
[super viewDidLoad];
[self.view addSubview:self.mapView];
[self coordinateTouch];
[self performSelector:@selector(gotoTouch) withObject:nil afterDelay:5];
}
- (void)coordinateTouch{
_locationManager = [[CLLocationManager alloc] init];
// [_locationManager requestWhenInUseAuthorization];
[_locationManager requestAlwaysAuthorization];//iOS8必须,这两行必须有一行执行,否则无法获取位置信息,和定位
// _locationManager.allowsBackgroundLocationUpdates = YES;
// 设置代理
_locationManager.delegate = self;
// 设置定位精确度到米
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
// 设置过滤器为无
_locationManager.distanceFilter = kCLDistanceFilterNone;
// 开始定位
[_locationManager startUpdatingLocation];//开始定位之后会不断的执行代理方法更新位置会比较费电所以建议获取完位置即时关闭更新位置服务
//初始化地理编码器
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
//当前位置
CLLocation *newLocation = locations[0];
CLLocationCoordinate2D oldCoordinate = newLocation.coordinate;
self.Coordinate2D=oldCoordinate;
[manager stopUpdatingLocation];
CLGeocoder *geocoder = [[CLGeocoder alloc]init];
[geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
for (CLPlacemark *place in placemarks) {
self.position = [NSString stringWithFormat:@"%@ %@ %@ %@",place.country,place.locality,place.subLocality,place.thoroughfare];
[_positionBtn setTitle:self.position forState:UIControlStateNormal];
break;
}
}];
}
- (void)gotoTouch {
//目的地
self.addressName = @"杭州滨江区政府";
CLGeocoder *geocode = [[CLGeocoder alloc] init];
[geocode geocodeAddressString:self.addressName completionHandler:^(NSArray *placemarks, NSError *error) {
if ([placemarks count ] > 0) {
//移除目前地图上得所有标注点
[_mapView removeAnnotations:_mapView.annotations];
}else {
NSLog(@"找不到此地址");
return ;
}
for (int i = 0; i< [placemarks count]; i++) {
CLPlacemark * placemark = placemarks[i];
//调整地图位置和缩放比例,第一个参数是目标区域的中心点,第二个参数:目标区域南北的跨度,第三个参数:目标区域的东西跨度,单位都是米
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(placemark.location.coordinate, 10000, 10000);
//重新设置地图视图的显示区域
[_mapView setRegion:viewRegion animated:YES];
// 实例化 MapLocation 对象
mapLocation * annotation = [[mapLocation alloc] init];
annotation.streetAddress = placemark.thoroughfare ;
annotation.city = placemark.locality;
annotation.state = placemark.administrativeArea ;
annotation.zip = placemark.postalCode;
annotation.coordinate = placemark.location.coordinate;
annotation.title=placemark.name;
self.address=placemark.location.coordinate;;
//把标注点MapLocation 对象添加到地图视图上,一旦该方法被调用,地图视图委托方法mapView:ViewForAnnotation:就会被回调
[_mapView addAnnotation:annotation];
//第一个坐标
CLLocation *current=[[CLLocation alloc] initWithLatitude:self.Coordinate2D.latitude longitude:self.Coordinate2D.longitude];
//第二个坐标
CLLocation *before=[[CLLocation alloc] initWithLatitude:self.address.latitude longitude:self.address.longitude];
// 计算距离
CLLocationDistance meters=[current distanceFromLocation:before];
NSLog(@"计算距离========= %.0f 米",meters);
}
}];
[self presentViewController:self.alertController animated:YES completion:nil];
}
-(UIAlertController *)alertController{
if (!_alertController) {
_alertController = [UIAlertController alertControllerWithTitle:@"请选择地图" message:nil
preferredStyle:UIAlertControllerStyleActionSheet ];
UIAlertAction *appleAction = [UIAlertAction actionWithTitle:@"苹果自带地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
MKMapItem *currentLocation = [MKMapItem mapItemForCurrentLocation];
CLLocationCoordinate2D Coordinate2D ;
Coordinate2D.latitude = self.address.latitude;
Coordinate2D.longitude = self.address.longitude;
MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:Coordinate2D addressDictionary:nil]];
toLocation.name = self.addressName;
[MKMapItem openMapsWithItems:@[currentLocation,toLocation] launchOptions:@{MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeDriving,MKLaunchOptionsShowsTrafficKey:[NSNumber numberWithBool:YES]}];
}];
UIAlertAction *tecentAction = [UIAlertAction actionWithTitle:@"高德地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
NSString *urlString = [[NSString stringWithFormat:@"iosamap://navi?sourceApplication=%@&backScheme=%@&poiname=%@&lat=%f&lon=%f&dev=0&style=2",@"住哪儿",@"FXTools",self.addressName,self.address.latitude,self.address.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:urlString]]) {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
}else{
}
}];
UIAlertAction *baiduAction = [UIAlertAction actionWithTitle:@"百度地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
NSString *urlString = [[NSString stringWithFormat:@"baidumap://map/direction?origin={{我的位置}}&destination=latlng:%f,%f|name:%@&mode=driving&coord_type=gcj02",self.address.latitude,self.address.longitude,self.addressName] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
if ([[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]]) {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
}else{
[MBProgressHUD showMessage:@"您的手机未安装百度地图"];
}
}];
UIAlertAction *tentAction = [UIAlertAction actionWithTitle:@"腾讯地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
NSString *urlString = [NSString stringWithFormat:@"qqmap://map/routeplan?type=drive&fromcoord=%f,%f&tocoord=%f,%f&policy=1",self.Coordinate2D.latitude,self.Coordinate2D.longitude,self.address.latitude,self.address.longitude];
if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:urlString]]) {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
}else{
}
}];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"退出" style:UIAlertActionStyleCancel handler:nil];
[_alertController addAction:appleAction];
[_alertController addAction:tecentAction];
[_alertController addAction:baiduAction];
[_alertController addAction:tentAction];
[_alertController addAction:cancelAction];
}
return _alertController;
}
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
@interface mapLocation : NSObject<MKAnnotation>
// 地图标点类必须实现 MKAnnotation 协议
// 地理坐标
@property (nonatomic ,readwrite) CLLocationCoordinate2D coordinate ;
//街道属性信息
@property (nonatomic , copy) NSString * streetAddress ;
// 城市信息属性
@property (nonatomic ,copy) NSString * city ;
// 州,省 市 信息
@property(nonatomic ,copy ) NSString * state ;
//邮编
@property (nonatomic ,copy) NSString * zip ;
@property (nonatomic, copy) NSString *title;
@end
网友评论