IOS開發之地圖與定位,ios開發地圖
使用定位服務: 設定app有訪問定位服務的許可權,首先要在info.plist檔案中添加以下liang'ti
1.NSLocationWhenInUseUsageDescription在使用應用期間
2.NSLocationAlwaysUsageDescription 始終
#import "ViewController.h"
#import <CoreLocation/CoreLocation.h> //定位服務
#import <MapKit/MapKit.h> //地圖介面
#import "WXAnnotation.h"
@interface ViewController ()<MKMapViewDelegate>
{
CLLocationManager *_manager;
MKMapView *_mapView;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//接下來建立一個對象來管理相關的定位服務
_manager = [[CLLocationManager alloc] init];
//manager判斷:手機是否開啟定位 / app是否有訪問定位的許可權
//[CLLocationManager locationServicesEnabled]; //手機是否開啟定位
//[CLLocationManager authorizationStatus]; //app訪問定位的許可權的狀態
if(![CLLocationManager locationServicesEnabled] || [CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedWhenInUse ){
[_manager requestWhenInUseAuthorization]; //向使用者請求訪問定位服務
}
//建立地圖
[self createMapView];
//建立圖釘
[self createAnnotationView];
}
- (void)createMapView
{
//建立MapView
_mapView = [[MKMapView alloc] initWithFrame:self.view.bounds];
//地圖的類型
_mapView.mapType = MKMapTypeStandard;
//顯示使用者當前的位置
_mapView.showsUserLocation = YES;
//是否定位(是否追終使用者的位置)
_mapView.userTrackingMode = MKUserTrackingModeFollow;
_mapView.delegate = self;
[self.view addSubview:_mapView];
}
//建立圖釘
- (void)createAnnotationView
{
//建立model對象
WXAnnotation *annotation = [[WXAnnotation alloc] init];
annotation.title = @"定位的位置";
annotation.subtitle = @"殺殺殺!";
//座標的結構體
CLLocationCoordinate2D coord = { 39.9927359964, 116.3965684639 };
//圖釘所在的座標位置
annotation.coordinate = coord;
//把標註添加給mapView
[_mapView addAnnotation:annotation];
}
//更新使用者的位置(地圖視圖的代理方法)
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
//根據經緯度設定MapView
//設定顯示的地區範圍,設定顯示的精度
//設定顯示的精度(比列尺)
MKCoordinateSpan span = MKCoordinateSpanMake(0.01, 0.01);
//指定的範圍
MKCoordinateRegion region = MKCoordinateRegionMake(userLocation.location.coordinate,span);
//移動mapView顯示的位置
[_mapView setRegion:region animated:YES];
}
//建立標註視圖的代理方法
/**
* 調用時機:annotation要添加到mapView上,座標出現在mapView中,就調用代理方法添加一個圖釘
*/
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
//目前使用者的位置,不顯示圖釘
if ([annotation isKindOfClass:[MKUserLocation class]]) {
return nil;
}
// MKAnnotationView 不能直接使用 (自訂圖釘視圖,繼承)
//MKPinAnnotationView能顯示的圖釘視圖
static NSString *iden = @"Annotation_view";
//圖釘視圖
MKPinAnnotationView *annotationView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:iden];
if (annotationView == nil) {
annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:iden];
//圖釘的顏色
annotationView.pinColor = MKPinAnnotationColorPurple;
//圖釘從天而降的動畫
annotationView.animatesDrop = YES;
//顯示內容
annotationView.canShowCallout = YES;
//輔助視圖
annotationView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
}
//重新設定圖釘視圖的model,解決重用的問題
annotationView.annotation = annotation;
return annotationView;
}