IOS開發學習記錄之高德地圖的學習1 定位,ios9的配置,添加標記點等。


1. 配置的問題

其實我個人覺得高德地圖沒有百度地圖好用,但是最初開始就是用的高德地圖,然后有些問題,但是不甘心放棄,所以就一直用高德地圖,自己解決了那些問題。

最近買了macbook,裝的xcode7,結果就不能定位了。提示如下:      

App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.

  原來是IOS9中更改了加密方式,解決辦法如下,在info.plist中添加App Transport Security Settings:

 

然后就可按着官方文檔進行環境的配置。但是運行時並不會定位,是因為ios8中系統corelocation框架發生了改變,中必須在info.plist加入一個string字段來才能定位,

NSLocationAlwaysUsageDescription  運行時持續定位。

NSLocationWhenInUseUsageDescription  進入后台就停止定位。  

都會彈出個提示框讓用戶決定是否同意定位。

 

2.定位的實現

  

/*首先必須使地圖可以顯示用戶當前位置,即可以在地圖中心顯示一個小圓點*/
/*然后執行定位的代理方法,在地位完成時獲取當前地址編碼*/
/*然后進行一個地理反編碼的操作,通過地圖搜索API,獲取當前地址的詳細信息*/
/*這里我學着用了下masonry,可以自己設置布局*/
#import "HomeViewController.h"
#import "Masonry.h"
@interface HomeViewController ()
@property (nonatomic,retain) MAMapView *mapView;
@end

@implementation HomeViewController
@synthesize mapView=_mapView;
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initView];
    // Do any additional setup after loading the view from its nib.
}
-(void)initView{
    UIView *superview=self.view;
    UIEdgeInsets padding=UIEdgeInsetsMake(10, 10, 10, 10);
    mapView=[[MAMapView alloc]init];
    search=[[AMapSearchAPI alloc]init];
    mapView.delegate=self;
    search.delegate=self;
    [superview addSubview:mapView];

    [mapView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(superview.mas_top).with.offset(padding.top); //with is an optional semantic filler
        make.left.equalTo(superview.mas_left).with.offset(padding.left);
        make.bottom.equalTo(superview.mas_bottom).with.offset(-padding.bottom);
        make.right.equalTo(superview.mas_right).with.offset(-padding.right);
    }];
    mapView.showsUserLocation=YES; //一定要可以顯示用戶地位點才可以
}
#pragma mark  定位
//開始定位時執行,將定位方式設置為跟隨模式即可定位
- (void)mapViewWillStartLocatingUser:(MAMapView *)mapview{
    mapView.userTrackingMode=MAUserTrackingModeFollow;
}
//定位失敗時執行
-(void)mapView:(MAMapView *)mapView didFailToLocateUserWithError:(NSError *)error{
     NSLog(@"%@",error);
}
//用戶地址發生更新后執行
- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation
{
    //將用戶地址傳入參數currentLocation
    currentLocation = [userLocation.location copy];
    //  NSLog(@"_currentLoaction:%@",currentLocation);
    //獲得當前地理編碼后,進行反編碼,獲得當前定位點的信息
    [self reGeoAction];
}
//地理反編碼函數
-(void)reGeoAction
{
    if (currentLocation) {
        //生成一個地理反編碼的搜索
        AMapReGeocodeSearchRequest *request = [[AMapReGeocodeSearchRequest alloc] init];
        
        request.location = [AMapGeoPoint locationWithLatitude:currentLocation.coordinate.latitude longitude:currentLocation.coordinate.longitude];
        [search AMapReGoecodeSearch:request];
    }
}
// 反編碼回調函數
- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response
{
    //將搜索結果傳給用戶定位點,這樣呼出氣泡就可以顯示出詳細信息
    NSString *title = response.regeocode.addressComponent.city;
    if (title.length ==0) {
        title = response.regeocode.addressComponent.province;
    }
    mapView.userLocation.title = title;
    mapView.userLocation.subtitle = response.regeocode.formattedAddress;
}
//反編碼時會進行一個搜索操作,搜索失敗時會執行這個方法
- (void)searchRequest:(id)request didFailWithError:(NSError *)error
{
    NSLog(@"request:%@,error:%@",request,error);
}

 

效果圖如下:

 

3 插入標記點

 

  插入標記點,其實就是向mapview添加一個個annotation,可以生成一個數組,然后存入這些annotation,一次性添加到地圖上。

  MAPointAnnotation是MAAnnotation的子類,它有CLLocationCoordinate2D,title,subtitle等屬性,分別指坐標,標題和副標題。標題和副標題就是默認顯示在彈出氣泡中的。默認下氣泡是可以彈出的。關於氣泡的自定義等設置,在下次博文中講解。

#pragma mark 設置標記點
//先網絡請求獲取需要的標記點的坐標,title和subtitle數據
-(void)requestData{
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    NSString *urlstr;
    if ([mapType isEqualToString:@"CDZ"]) {
        urlstr =checkCDZUrl;
    }
    else if ([mapType isEqualToString:@"WXZ"]){
        urlstr=checkWXZUrl;
    }
    NSDictionary *parameters=@{@"PoleState":@"",@"PoleAddress":@"武漢",@"PoleName":@"",@"PoleStyle":@""};
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:urlstr parameters:parameters error:nil];
    NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (error) {
            NSLog(@"Error: %@", error);
        } else {
            _AnnotationsArr=[NSMutableArray new];
            _DataArr=[responseObject objectForKey:@"Content"];
            NSDictionary *dic;
            for (int i=0;i<_DataArr.count;i++) {
                dic=_DataArr[i];
        //這里我們在循環中每次新生成一個MAPointAnnotation來做標記點
                MAPointAnnotation *poi=[[MAPointAnnotation alloc]init];
        //給標記點傳入title和subtitle
                poi.title=[dic objectForKey:@"PoleName"];
                poi.subtitle=[dic objectForKey:@"PoleAdress"];
                NSString *degreeStr=[dic objectForKey:@"PoleFix"];
        //最重要的是坐標
                NSArray *components = [degreeStr componentsSeparatedByString:@","];
                CLLocationDegrees latitude=[components[0]doubleValue];
                CLLocationDegrees longitude=[components[1]doubleValue];
                poi.coordinate=CLLocationCoordinate2DMake(latitude,longitude);
                //然后將這些標記點存入可變數組中
                [_AnnotationsArr addObject:poi];
            }
            //再將全部標記點一次插入地圖
                [mapView addAnnotations:_AnnotationsArr];
        }}];
    [dataTask resume];
}
-(void)SearchPoi{
    
}
#pragma mark MAMapView-delegate
//這是標記點實現的代理方法,就如同tableview的cellfor方法,可以再該方法中置
//標記點的樣式等等屬性,自定義標記點也要在此方法中實現
-(MAAnnotationView*)mapView:(MAMapView *)mapview viewForAnnotation:(id<MAAnnotation>)annotation{
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        
        static NSString *reuseId=@"identifier";
        MAPinAnnotationView *an=(MAPinAnnotationView*)[mapview dequeueReusableAnnotationViewWithIdentifier:reuseId];
        if (an==nil) {
            an=[[MAPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:reuseId];
        }
    //點擊可以彈出氣泡
        an.canShowCallout=YES;
    //自己設置標記點的圖片,這里我用了一個分類來改變素材的大小
        UIImage *image=[UIImage imageNamed:@"map-marker1"];
        CGSize imagesize=CGSizeMake(30, 30);
        an.image=[image imageByScalingToSize:(imagesize)];
        return an;
    }
    return nil;
}

 

效果圖如下:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM