廢話不說次乓,直接上代碼
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
@interface PositionController ()<CLLocationManagerDelegate,MKMapViewDelegate>
{
//添加代理協(xié)議 CLLocationManagerDelegate
CLLocationManager *_locationManager;//定位服務管理類
}
@property (nonatomic, strong)NSString *position;//現(xiàn)在位置
@property (nonatomic, assign)CLLocationCoordinate2D Coordinate2D;//現(xiàn)在的坐標
@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, // 衛(wèi)星
MKMapTypeHybrid, // 混合(標準+衛(wèi)星)
MKMapTypeSatelliteFlyover NS_ENUM_AVAILABLE(10_11, 9_0), // 3D立體衛(wèi)星
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必須,這兩行必須有一行執(zhí)行婚夫,否則無法獲取位置信息澄步,和定位
// _locationManager.allowsBackgroundLocationUpdates = YES;
// 設置代理
_locationManager.delegate = self;
// 設置定位精確度到米
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
// 設置過濾器為無
_locationManager.distanceFilter = kCLDistanceFilterNone;
// 開始定位
[_locationManager startUpdatingLocation];//開始定位之后會不斷的執(zhí)行代理方法更新位置會比較費電所以建議獲取完位置即時關閉更新位置服務
//初始化地理編碼器
}
- (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 = @"杭州濱江區(qū)政府";
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];
//調整地圖位置和縮放比例,第一個參數(shù)是目標區(qū)域的中心點裸违,第二個參數(shù):目標區(qū)域南北的跨度呢岗,第三個參數(shù):目標區(qū)域的東西跨度,單位都是米
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(placemark.location.coordinate, 10000, 10000);
//重新設置地圖視圖的顯示區(qū)域
[_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>
// 地圖標點類必須實現(xiàn) MKAnnotation 協(xié)議
// 地理坐標
@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