iOS - 在应用程序启动时缩放到当前用户位置
我想在启动时将地图缩放到当前用户位置。我尝试在viewDidLoad上使用mapView.userLocation.coordinate检索用户位置,但返回的坐标为(0,0),可能是因为MapKit在启动时不会“查找”用户位置。iOS - 在应用程序启动时缩放到当前用户位置
我发现了一个实现方法didUpdateToLocation的解决方案。我做了以下内容:
- (void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
if (hasZoomedAtStartUp == NO)
{
[self zoomAtStartUp]; // my method to zoom the map
hasZoomedAtStartUp = YES;
}
}
我在.h文件中创建并在viewDidLoad中NO initialied它的hasZoomedAtStartUp变量。
此解决方案工作正常,但我想知道是否有另一种方法来做到这一点,没有if语句。 IF与startUp相关的justo,所以我想删除它,出于性能原因。
我非常怀疑一个失败的陈述是你需要担心的表现。
您是否需要经常使用位置服务?如果不是,当您不再需要更新位置时,您可能会从调用stopUpdatingLocation获得更大的收益。随后,您甚至不会到达didUpdateToLocation,因为您不再获取新的位置数据。
您现在使用的方法-locationManager:didUpdateToLocation:fromLocation
是对用户位置进行任何操作的最佳位置。有几件事情,我会尽你的不同。
首先,您接受第一次位置更新为最佳。你可能要求一定的准确性,但要求它并不意味着该方法的newLocation
是最好的。通常情况下,你会得到一个非常低的准确性,或者从过去的某个时间点的缓存位置。我会做的是检查新的位置的年龄和准确性,只有当它的放大。
我会做的另一件事是关闭位置更新,无论是当更新具有良好的准确性在更新开始后30秒内。设置一个计时器将其关闭,当您关闭计时器时,请设置一个较长的计时器将其重新打开并再次检查。
最后,请确保您已正确实施所有情况下的-locationManager:didFailWithError:
。这一直是您提交应用程序时所测试的一件事情。如果它没有失败(例如,在飞行模式下),它可能会被拒绝。
围绕堆栈溢出搜索技术和代码来完成这些事情。
您可以随时进行初始化并开始获取位置更新。该CLLocationManager会通知您的委托,每当一个新的位置,接收 并设置在地图上的区域该位置显示
//Don't Forget To Adopt CLLocationManagerDelegate protocol
//set up the Location manager
locationManager = [[CLLocationManager alloc] init];
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = DISTANCE_FILTER_VALUE;
locationManager.delegate = self;
[locationManager startUpdatingLocation]
//WIll help to get CurrentLocation implement the CLLocationManager delegate
- (void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
// use this newLocation .coordinate.latitude
}
// set Span
MKCoordinateSpan span;
//You can set span for how much Zoom to be display like below
span.latitudeDelta=.005;
span.longitudeDelta=.005;
//set Region to be display on MKMapView
MKCoordinateRegion cordinateRegion;
cordinateRegion.center=latAndLongLocation.coordinate;
//latAndLongLocation coordinates should be your current location to be display
cordinateRegion.span=span;
//set That Region mapView
[mapView setRegion:cordinateRegion animated:YES];
,您可根据“初始”委托执行,你可以缩放到位置后注销,并注册你的'普通'代表现在不需要整个缩放,如果有的话。
我一直需要位置服务,因为我正在开发(实际上是为了学习)基于地图的应用程序。 If语句不是一个很大的性能问题,但是,因为我总是需要它,所以它可能是。我想知道我是否可以在其他地方执行此任务,因为我只需要一次(在startUp)。 – Beraldo 2012-02-26 15:59:08
@尼克,不,我不同意你的观点,如果有人不需要经常定位服务,那就没有问题。我们只需要正确编程didUpdateToLocation和stopUpdatingLocation方法两者。我们可以做到这一点,假设我们在特定的(A)上显示CurrentLocation。然后,我们只需要从ViewLoadingTime调用didUpdateToLocation并在View中调用stopUpdatingLocation去disAppear( - (void )viewWillDisappear:(BOOL)动画方法。)。 – Kamarshad 2012-02-29 10:41:13