標籤:android des style blog class code
定位服務是通過GPS等方式尋找定位自己的位置的,再通過地表徵圖注出來。
在iOS中定位服務和地圖開發是使用兩套API分別完成的。
1、定位服務:
iOS系統提供3種不同定位途徑:
1>WiFi定位:通過查詢一個WiFi路由器的地理位置資訊,iPhone、iPod Touch、iPad都可以採用。
2>蜂窩式行動電話基站定位:通過行動電信業者基站定位
3>GPS衛星定位:通過3~4顆GPS衛星位置定位,最為準確,但是耗電量大
iOS不像Android系統在定位服務編程時可以指定採用哪種途徑進行定位。iOS的API把底層這些細節屏蔽掉了,開發人員和使用者並不知道現在裝置採用哪種方式進行定位,iOS系統會根據裝置的情況和周圍環境,採用一套最佳的解決方案。具體是:如果能夠GPS資訊,那麼裝置優先採用GPS定位,否則採用WiFi或蜂窩基站定位,在WiFi和蜂窩基站之間優先使用WiFi,如果無法串連到WiFi才使用蜂窩基站定位。
1.1、定位服務編程
在iOS 6之後,定位服務主要使用CoreLocaation架構,定位時主要使用CLLocationManager、CLLocationManagerDelegate和CCLocation。
CLLocationManager類:定位服務管理類,它能夠使我們獲得裝置的位置資訊和高度資訊,也可以監控裝置進入某個地區,還可以協助我們獲得裝置的運行方向。
CLLocationManagerDelegate類:是CLLocationManager類的委託協議。
CLLocation類:封裝了位置和高度資訊。
下面具體操作:
第一步,建立一個singleView的空白工程
第二步:向工程中引入framework:CoreLocation.framework
在主介面的控制器 ViewController.h 檔案中,我們啥也不做,.m檔案中,我們需聲明一個 CLLocationManager* locationManager的屬性,我們讓其實現CLLocationManagerDelegate的協議,並實現代理方法didUpdateLocations和didFailWithError,如下://// ViewController.m
// CLLocationManager//// Created by apple on 14-5-11.// Copyright (c) 2014年 姚新超. All rights reserved.//#import "ViewController.h"#import <CoreLocation/CoreLocation.h>@interface ViewController ()<CLLocationManagerDelegate>{ }@property (nonatomic,strong) CLLocationManager* locationManager;@end@implementation ViewController
- (void)viewDidLoad{ [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib.
// 定位服務管理對象初始化
self.locationManager = [[CLLocationManager alloc] init]; //delegate self.locationManager.delegate = self; //The desired location accuracy. self.locationManager.desiredAccuracy = kCLLocationAccuracyBest; //Specifies the minimum update distance in meters. self.locationManager.distanceFilter = kCLDistanceFilterNone; self.locationManager.purpose = @"To provide functionality based on user‘s current location.";}- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animatted];
// 開始定位
[self.locationManager startUpdatingLocation];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
// 停止定位
[self.locationManager stopUpdatingLocation];
}@end
#pragma mark - 委託方法用於實現位置的更新- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{ // 裝置的當前位置 CLLocation *currLocation = [locations lastObject]; NSString *latitude = [NSString stringWithFormat:@"緯度:%3.5f",currLocation.coordinate.latitude]; NSString *longitude = [NSString stringWithFormat:@"經度:%3.5f",currLocation.coordinate.longitude]; NSString *altitude = [NSString stringWithFormat:@"高度值:%3.5f",currLocation.altitude];}- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{ NSLog(@"error : %@",error.localizedDescription);}
locationManager: didUpdateLocations:iOS 6新增方法,定位成功時調用,用於替代之前的locationManager:didUpdateToLocation:fromLocation:方法。
locationManager: didFailWithError:定位失敗。