iOS原生地圖與高德地圖的使用


原生地圖

1、什么是LBS

LBS: 基於位置的服務 Location Based Service

實際應用:大眾點評,陌陌,微信,美團等需要用到地圖或定位的App

2、定位方式

1.GPS定位 2.基站定位 3.WIFI定位

3、框架

MapKit:地圖框架,顯示地圖

CoreLocation:定位框架,沒有地圖時也可以使用定位.

4、如何使用原生地圖 和定位

MapKit:

  1. 初始化MapView

    _mapView = [[MKMapView alloc] initWithFrame:self.view.bounds];

    [self.view addSubview:_mapView];

  2. 設置代理

_mapView.delegate = self;

  1. 設置地圖類型

    _mapView.mapType = MKMapTypeStandard;

  2. 允許顯示自己的位置

    _mapView.showsUserLocation = YES;

  3. 設置地圖中心坐標點

    CLLocationCoordinate2D centerCoordinate = CLLocationCoordinate2DMake(22.540396,113.951832);

    _mapView.centerCoordinate = centerCoordinate;

  4. 設置地圖顯示區域

a) 設置縮放

 MKCoordinateSpan span = MKCoordinateSpanMake(0.1, 0.1);

b) 設置區域

MKCoordinateRegion region = MKCoordinateRegionMake(centerCoordinate, span);

c) 顯示區域

_mapView.region = region;

CoreLocation:

  1. 初始化定位管理器

_manager = [[CLLocationManager alloc] init];

_manager.delegate = self;

  1. iOS8定位
  1. 在info.plist中添加 Privacy - Location Usage Description , NSLocationAlwaysUsageDescription

  2. 在代碼中加入

    if ( [UIDevice currentDevice].systemVersion.floatValue >= 8.0 ) {

       [_manager requestAlwaysAuthorization];
    

    }

  1. 開啟定位

    [_manager startUpdatingLocation];

  2. 定位成功代理

  • (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations

{

  NSLog(@"定位成功");



  //獲取定位的坐標

  CLLocation *location = [locations firstObject];



  //獲取坐標

  CLLocationCoordinate2D coordinate = location.coordinate;

  NSLog(@"定位的坐標:%f,%f", coordinate.longitude, coordinate.latitude);



  //停止定位

  //[_manager stopUpdatingLocation];

}

  1. 定位失敗代理
  • (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error

{

  NSLog(@"定位失敗”);

}

  1. 屏幕坐標轉經緯度坐標

    CLLocationCoordinate2D cl2d = [_mapView convertPoint:point toCoordinateFromView:_mapView];

  2. 反地理編碼

    CLGeocoder *geocoder = [[CLGeocoder alloc] init];

    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {

//獲取地標對象

      CLPlacemark *mark = [placemarks firstObject];

 }];

大頭針(標注):

  1. 添加大頭針

    //創建大頭針

    MKPointAnnotation *pointAnn = [[MKPointAnnotation alloc] init];

    //設置坐標

    pointAnn.coordinate = CLLocationCoordinate2DMake(23.181297, 113.346877);

    //設置標題

    pointAnn.title = @"我的第一個大頭針";

    //設置副標題

    pointAnn.subtitle = @"副標題";

    //顯示大頭針,把大頭針加入到地圖上

    [_mapView addAnnotation:pointAnn];

  2. 大頭針的復用及定制

pragma mark - mapView 代理方法

//大頭針View

-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id )annotation

{

//如果是自己當前位置的大頭針,則不定制

if ( [annotation isKindOfClass:[MKUserLocation class]]) {

    return  nil;

}

if 1

// 1、自帶的大頭針視圖

MKPinAnnotationView *pinAnnView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:@"ID"];

if ( !pinAnnView ) {

    pinAnnView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"ID"];

}



//設置大頭針的顏色

pinAnnView.pinColor = MKPinAnnotationColorPurple;



//設置掉落動畫

pinAnnView.animatesDrop = YES;



//是否彈出氣泡

pinAnnView.canShowCallout = YES;



//設置左視圖

UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];

leftView.backgroundColor = [UIColor blueColor];

pinAnnView.leftCalloutAccessoryView = leftView;



//設置右視圖

UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];

pinAnnView.rightCalloutAccessoryView = rightBtn;





return  pinAnnView;

else

//2、自定義大頭針視圖

/*

   * 區別於MKPinAnnotationView

   * 1、可以設置大頭針圖片

   * 2、不可以設置大頭針顏色和掉落動畫

   */



MKAnnotationView *customView = [mapView dequeueReusableAnnotationViewWithIdentifier:@"ID2"];

if ( !customView ) {

    customView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"ID2"];

}



//設置點擊大頭針可以顯示氣泡

customView.canShowCallout = YES;



//設置大頭針圖片

customView.image = [UIImage imageNamed:@"marker"];



//設置左視圖

UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];

leftView.backgroundColor = [UIColor blueColor];

customView.leftCalloutAccessoryView = leftView;



//設置右視圖

UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];

customView.rightCalloutAccessoryView = rightBtn;





return  customView;

endif

}

  1. 移除大頭針

    [_mapView removeAnnotations:_mapView.annotations];

  2. 添加長按手勢,實現在地圖的長按點添加一個大頭針

//4、長按地圖顯示大頭針

UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];

[_mapView addGestureRecognizer:longPress];

pragma mark - 長按手勢

-(void)longPress:(UILongPressGestureRecognizer *)gesture

{

//避免多次調用 只允許開始長按狀態才添加大頭針

if (gesture.state != UIGestureRecognizerStateBegan) {

    return;

}



//獲取長按地圖上的某個點

CGPoint point = [gesture locationInView:_mapView];



//把point轉換成在地圖上的坐標經緯度

CLLocationCoordinate2D coordinate = [_mapView convertPoint:point toCoordinateFromView:_mapView];



//添加長按的大頭針

MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];

annotation.coordinate = coordinate;

annotation.title = @"長按的大頭針";

annotation.subtitle = @"副標題";

[_mapView addAnnotation:annotation];

}

高德地圖

1、高德地圖申請Appkey流程:

a) 在瀏覽器中打開網址:http://lbs.amap.com/api/ios-sdk/guide/verify/

b) 訪問:http://lbs.amap.com/console/key/,使用高德開發者賬號登陸

c) 2.在“KEY管理”頁面點擊上方的“獲取key”按鈕,依次輸入應用名,選擇綁定的服務為“iOS平台SDK”,輸入Bundle Identifier(Bundle Identifier獲取方式為Xcode->General->Identity)

2、高德地圖配置工程流程:

a)下載高德地圖iOS SDK

b)添加高德地圖的庫文件MAMapKit.framework

c)添加8個關聯庫QuartzCore, CoreLocation, SystemConfiguration, CoreTelephony, libz, OpenGLES, libstdc++6.09, Security(MAMapView)

d)添加AMap.bundle(MAMapKit.framework->Resources)

e) TARGETS-Build Settings-Other Linker Flags 中添加內容: -ObjC;

f)在代碼中添加用戶Key: [MAMapServices sharedServices].apiKey =@"您的key";

3、單獨使用搜索服務包:

a)添加搜索庫文件AMapSearchKit.framework

b)添加關聯庫SystemConfiguration, CoreTelephony, libz, libstdc++6.09

c)在代碼中添加AMapSearchAPI *search = [[AMapSearchAPI alloc] initWithSearchKey: @"您的key" Delegate:self];

4、如何使用高德地圖 和 搜索

MAMapKit:

  1. 配置高德地圖API

define APIKEY @"e848d391f9c4b98db0935052777f99d2"

 [MAMapServices sharedServices].apiKey = APIKEY;
  1. 初始化MAMapView

_maMapView = [[MAMapView alloc] initWithFrame:self.view.bounds];

 [self.view addSubview:_maMapView];  
  1. 設置代理

    _maMapView.delegate = self;

  2. 設置地圖類型

    _maMapView.mapType = MAMapTypeStandard;

  3. 允許顯示自己的位置(如使用定位功能,則必須設置為YES)

    _maMapView.showsUserLocation = YES;

  4. 設置logo位置

    _maMapView.logoCenter = CGPointMake(100, 100);

  5. 顯示羅盤

    _maMapView.showsCompass = YES;

  6. 顯示交通

    _maMapView.showTraffic = YES;

  7. 是否支持旋轉

    _maMapView.rotateEnabled = YES;

  8. 是否支持拖動

    _maMapView.scrollEnabled = YES;

  9. 是否支持縮放

_maMapView.zoomEnabled = NO;
  1. 設置地圖顯示區域

a) 設置坐標

CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(23.181297, 113.346877);

b) 設置縮放

MACoordinateSpan span = MACoordinateSpanMake(0.1, 0.1);

c) 設置區域

MACoordinateRegion region = MACoordinateRegionMake(coordinate, span);

d) 顯示區域

_maMapView.region = region;
  1. 定位

pragma mark - 定位 回調方法

-(void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation

{

  NSLog(@"定位成功");



  CLLocation *location = userLocation.location;

  CLLocationCoordinate2D coordinate = location.coordinate;



  NSLog(@"我的坐標位置:%f, %f", coordinate.longitude, coordinate.latitude);



  // 定位后,可設置停止定位

  // _maMapView.showsUserLocation = NO;

}

  1. 添加標注(大頭針)
//添加標注

  MAPointAnnotation *annotation = [[MAPointAnnotation alloc] init];

  annotation.coordinate = coordinate; //設置標注的坐標

  annotation.title = @"高德地圖標題"; //設置標題

  annotation.subtitle = @"副標題"; //設置副標題

  [_maMapView addAnnotation:annotation]; //將標注添加在地圖上
  1. 標注的復用及定制

pragma mark - 定制標注視圖(和原生地圖定制方式類似)

  • (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id )annotation

{

  //不定制自己位置的標注視圖

  if ( [annotation isKindOfClass:[MAUserLocation class]]) {

      return nil;

  }

if 1

  // 1、自帶的標注視圖

  MAPinAnnotationView *pinAnnView = (MAPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:@"ID"];

  if ( !pinAnnView ) {

      pinAnnView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"ID"];

  }



  // 是否可彈出視圖

  pinAnnView.canShowCallout = YES;



  // 設置掉落動畫

  pinAnnView.animatesDrop = YES;



  // 設置標注顏色

  pinAnnView.pinColor = MAPinAnnotationColorGreen;



  // 設置左視圖

  UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];

  leftView.backgroundColor = [UIColor blueColor];

  pinAnnView.leftCalloutAccessoryView = leftView;



  //設置右視圖

  UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];

  pinAnnView.rightCalloutAccessoryView = rightBtn;



  return pinAnnView;

else

  //2、自定義標注視圖

  MAAnnotationView *customView = [mapView dequeueReusableAnnotationViewWithIdentifier:@"ID2"];

  if ( !customView ) {

      customView = [[MAAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"ID2"];

  }



  //設置點擊大頭針可以顯示氣泡

  customView.canShowCallout = YES;



  //設置大頭針圖片

  customView.image = [UIImage imageNamed:@"marker"];



  //設置左視圖

  UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];

  leftView.backgroundColor = [UIColor blueColor];

  customView.leftCalloutAccessoryView = leftView;



  //設置右視圖

  UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];

  customView.rightCalloutAccessoryView = rightBtn;



  return  customView;

endif

}

  1. 添加長按手勢

    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];

    [_maMapView addGestureRecognizer:longPress];

pragma mark -- 長按手勢Action

-(void)longPress:(UILongPressGestureRecognizer *)longPress

{

  if (longPress.state != UIGestureRecognizerStateBegan) {

      return;

  }



  //獲取點位置

  CGPoint point = [longPress locationInView:_maMapView];



  //將點位置轉換成經緯度坐標

  CLLocationCoordinate2D coordinate = [_maMapView convertPoint:point toCoordinateFromView:_maMapView];



  //在該點添加一個大頭針(標注)

  MAPointAnnotation *pointAnn = [[MAPointAnnotation alloc] init];

  pointAnn.coordinate = coordinate;

  pointAnn.title = @"長按的大頭針";

  pointAnn.subtitle = @"副標題";

  [_maMapView addAnnotation:pointAnn];

}

AMapSearchKit:

  1. 搜索周邊

  2. 創建AMapSearchAPI對象,配置APPKEY,同時設置代理對象為self

    searchAPI = [[AMapSearchAPI alloc] initWithSearchKey:APIKEY Delegate:self];

a) 創建搜索周邊請求類

AMapPlaceSearchRequest *searchRequest = [[AMapPlaceSearchRequest alloc] init];

b) 設置搜索類型(按關鍵字搜索)

searchRequest.searchType = AMapSearchType_PlaceKeyword;

c) 設置關鍵字

searchRequest.keywords = keywordsTextField.text;

d) 設置搜索城市

searchRequest.city = @[@"廣州"];

e) 開始搜索

[searchAPI AMapPlaceSearch:searchRequest];
  1. 搜索周邊回調方法

a) 搜索失敗

  • (void)searchRequest:(id)request didFailWithError:(NSError *)error

{

NSLog(@"搜索失敗");

}

b) 搜索成功

-(void)onPlaceSearchDone:(AMapPlaceSearchRequest *)request response:(AMapPlaceSearchResponse *)response

{

//清空原來的標注(大頭針)

[_maMapView removeAnnotations:_maMapView.annotations];



//判斷是否為空

if (response) {

    

    //取出搜索到的POI(POI:Point Of Interest)

    for (AMapPOI *poi in response.pois) {

        

        //poi的坐標

        CLLocationCoordinate2D coordinate = 

CLLocationCoordinate2DMake(poi.location.latitude, poi.location.longitude);

        //地名

        NSString *name = poi.name;

        

        //地址

        NSString *address = poi.address;

        

        //用標注顯示

        MAPointAnnotation *pointAnn = [[MAPointAnnotation alloc] init];

        pointAnn.coordinate = coordinate;

        pointAnn.title = name;

        pointAnn.subtitle = address;

        [_maMapView addAnnotation:pointAnn];

    }

}

}

  1. 添加折線

pragma mark - 畫折線

-(void)drawPolyLine

{

//初始化點

NSArray *latitudePoints =[NSArray arrayWithObjects:

                          @"23.172223",

                          @"23.163385",

                          @"23.155411",

                          @"23.148765",

                          @"23.136935", nil];

NSArray *longitudePoints = [NSArray arrayWithObjects:

                            @"113.348665",

                            @"113.366056",

                            @"113.366128",

                            @"113.362391",

                            @"113.356785", nil];



// 創建數組

CLLocationCoordinate2D polyLineCoords[5];



for (int i=0; i<5; i++) {

    polyLineCoords[i].latitude = [latitudePoints[i] floatValue];

    polyLineCoords[i].longitude = [longitudePoints[i] floatValue];



}



// 創建折線對象

MAPolyline *polyLine = [MAPolyline polylineWithCoordinates:polyLineCoords count:5];



// 在地圖上顯示折線

[_maMapView addOverlay:polyLine];

}

pragma mark - 定制折線視圖

-(MAOverlayView *)mapView:(MAMapView *)mapView viewForOverlay:(id )overlay

{

if ([overlay isKindOfClass:[MAPolyline class]]) {

    

    MAPolylineView *polyLineView = [[MAPolylineView alloc] initWithPolyline:overlay];

    polyLineView.lineWidth = 2; //折線寬度

    polyLineView.strokeColor = [UIColor blueColor]; //折線顏色

    polyLineView.lineJoinType = kMALineJoinRound; //折線連接類型

    

    return polyLineView;

}

return nil;

}


免責聲明!

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



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