iOS開發--添加定位功能

來源:互聯網
上載者:User

標籤:

.h

首先在標頭檔中#import <CoreLocation/CoreLocation.h>

添加CLLocationManagerDelegate協議

@property (strong, nonatomic) IBOutlet CLLocationManager *myLocationManager;

.m

在- (void)viewDidLoad添加以下代碼:

  self.myLocationManager=[[CLLocationManager alloc]init];
  [self.myLocationManager requestWhenInUseAuthorization];
  self.myLocationManager.delegate=self;
  //設定精度
  self.myLocationManager.desiredAccuracy=kCLLocationAccuracyBest;
  //設定定位服務更新頻率
  self.myLocationManager.distanceFilter=50;
  [self.myLocationManager startUpdatingLocation];

添加方法

//定位服務
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
  NSLog(@"GPS is here");
  CLLocation *location=[locations firstObject];//取出第一個位置
  CLLocationCoordinate2D coordinate=location.coordinate;//位置座標
  NSLog(@"經度:%f,緯度:%f,海拔:%f,航向:%f,行走速度:%f",coordinate.longitude,coordinate.latitude,location.altitude,location.course,location.speed);
  float a=coordinate.latitude;
  float b=coordinate.longitude;
  AGSPoint *point=[AGSPoint new];
  point=[AGSPoint pointWithX:b y:a spatialReference:self.mapView.spatialReference];
  AGSSimpleMarkerSymbol *mySymbol=[AGSSimpleMarkerSymbol simpleMarkerSymbol];
  mySymbol.color = [UIColor blueColor];
  mySymbol.outline.color=[UIColor redColor];
  mySymbol.outline.width=1;

  AGSGraphic *g=[AGSGraphic new];
  g=[AGSGraphic graphicWithGeometry:point symbol:mySymbol attributes:nil];
  [self.graphicsLayer addGraphic:g];
  [self.mapView addMapLayer:self.graphicsLayer withName:@"GPS"];

  //地圖放大到點
  //擷取最大值,最小值

  //設定參數求結果的最小外接矩形
  double xmin=DBL_MAX;
  double ymin=DBL_MAX;
  double xmax=-DBL_MAX;
  double ymax=-DBL_MAX;
  //設定地圖顯示範圍
  xmin=b-0.01;
  ymin=a-0.01;
  xmax=b+0.01;
  ymax=a+0.01;
  AGSMutableEnvelope *extent=[AGSMutableEnvelope envelopeWithXmin:xmin ymin:ymin xmax:xmax ymax:ymax   spatialReference:self.mapView.spatialReference];
  [extent expandByFactor:1.5];
  [self.mapView zoomToEnvelope:extent animated:YES];
  //如果不需要即時定位,使用完即使關閉定位服務
  [self.myLocationManager stopUpdatingLocation];
}

iOS開發--添加定位功能

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.