这个问题已经在这里有一个答案:
- 如何获取到当前安置位置在地图上iphone 2回答
我不能让当前的位置。 当我启动我的应用程序在不同的地方,应用程序可以得到最后一个位置。 但我不希望最后的位置。 如果您关闭应用程序并重新启动它,现在的应用程序可以获取当前位置。 我怎样才能得到哪怕是第一次启动应用程序的当前位置?
- (void)viewDidLoad
{
[super viewDidLoad];
[locationManager startUpdatingLocation];
self.mapView.delegate = self;
[self.mapView setShowsUserLocation:YES];
locationManager.delegate=self;
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate=self;
locationManager.desiredAccuracy=kCLLocationAccuracyBest;
locationManager.distanceFilter=kCLDistanceFilterNone;
location = [locationManager location];
CLLocationCoordinate2D coord;
coord.longitude = location.coordinate.longitude;
coord.latitude = location.coordinate.latitude;
lat = coord.latitude;
longt = coord.longitude;
}
你是做[locationManager startUpdatingLocation];
前设置其委托
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate=self;
locationManager.desiredAccuracy=kCLLocationAccuracyBest;
locationManager.distanceFilter=kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
并实现它的委托方法
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
}
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error
{
}
为了得到当前的位置以及它的坐标,你只是只有这做你viewDidLoad
方法:
- (void)viewDidLoad {
[super viewDidLoad];
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
[locationManager startUpdatingLocation];
}
而关于更新位置,使用此方法:
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation{
// your code here...
}
你应该阅读提供的文档位置感知编程指南 。
特别是,当你问当前位置,系统将返回最后已知位置的时候了,所以你可以用它做什么有用的。 如果你不关心过去的位置,可以丢弃它,并且只通过查看使用更近的位置信息timestamp
的财产CLLocation
返回,以确定它是多么的近。
你真的应该阅读CLLocationManager
文档。
笏你正在做是行不通的,因为它需要一定的时间确定设备位置。 为此,你需要等到CLLocationManager
通知您的位置一直是威慑。
你将需要实现CLLocationManagerDelegate
它会告诉你,如果位置是威慑,或者位置确定失败。
另外你还应该检查是否位置可以威慑与:
if ([CCLocationManager locationServicesEnabled]) {
// The location services are available.
}
您也应该检查无论您是授权与使用位置服务[CCLocationManager authorizationStatus]