取得所在位置是行動裝置的一大特色,在地化、導航、語言、文化都跟這服務脫離不了關係,在iOS中使用這服務需要先import一個framework如下
加入framework後還必須加入CoreLocation的Delegate,以及因為下面範例中使用者如果將定位服務關閉彈出Alert詢問使用者是否將開啟定位服務,需要加入的Delegate如下(在.h檔中)
加入後應該會看到錯誤,因為CoreLocation這framework還沒被import,必須在.h檔上方先import這行
使用的方式如下(.m檔)
相關連結
iOS Developer Library
iOS Developer Library - CoreLocation Framework
CoreLocation.framework
加入framework後還必須加入CoreLocation的Delegate,以及因為下面範例中使用者如果將定位服務關閉彈出Alert詢問使用者是否將開啟定位服務,需要加入的Delegate如下(在.h檔中)
CLLocationManagerDelegate, UIAlertViewDelegate
加入後應該會看到錯誤,因為CoreLocation這framework還沒被import,必須在.h檔上方先import這行
#import <CoreLocation/CoreLocation.h>
使用的方式如下(.m檔)
//初始化LocationService
-(void) openLocationService{
//location
CLLocationManager *locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
[locationManager startUpdatingLocation];
}
//給地址、經緯度後直接開啟Google map導航
-(void)navivationToTheAddress:(NSString *)address myLatitude:(double)latitude myLongitude:(double)longitude{
NSString* urlString = [NSString stringWithFormat:@"http://maps.google.com/maps?f=d&source=s_d&saddr=%f,%f&daddr=%@", latitude, longitude, address];
NSString *escaped = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:escaped]];
}
//location Delegate
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
NSString *address = [self.myWebView stringByEvaluatingJavaScriptFromString:@"naviAddress"];
[self navivationToTheAddress:address myLatitude:manager.location.coordinate.latitude myLongitude:manager.location.coordinate.longitude];
[manager stopUpdatingLocation];
}
//錯誤發生時回報方式
-(void) locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
//NSLog(@"didFailWithError = %@", error);
NSString *errorString;
[manager stopUpdatingLocation];
NSLog(@"Error: %@",[error localizedDescription]);
switch([error code]) {
case kCLErrorDenied:
errorString = @"您已關閉定位服務無法順利導航,是否立即開啟服務?";
break;
case kCLErrorLocationUnknown:
errorString = @"無法順利取得您的位置";
break;
default:
errorString = @"無法順利取得您的位置";
break;
}
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Golf球場指南" message:errorString delegate:self cancelButtonTitle:@"收後啟用" otherButtonTitles:@"立即啟用", nil];
[alert show];
}
-(void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
NSLog(@"clickedButtonAtIndex buttonIndex = %d", buttonIndex);
if(buttonIndex == 1){
//點選"立即開啟"後打開設定中的定位服務開啟畫面
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=LOCATION_SERVICES"]];
}
}
相關連結
iOS Developer Library
iOS Developer Library - CoreLocation Framework
沒有留言:
張貼留言