標籤:
.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開發--添加定位功能