[英]iOS - Zoom to the current user location at app start up
我想在启动时将地图缩放到当前用户位置。 我试图在viewDidLoad中使用mapView.userLocation.coordinate来检索用户位置,但返回的坐标是(0,0),可能是因为MapKit在启动时没有“找到”用户位置。
我找到了一个实现方法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文件中创建的hasZoomedAtStartUp变量,并在ViewDidLoad中用NO初始化它。
这个解决方案工作正常,但我想知道是否有另一种方法可以做到这一点,没有if语句。 这个IF对于startUp是相关的,所以我想删除它,出于性能原因。
我非常怀疑一个失败的if语句是你需要担心的性能。
您是否经常需要定位服务? 如果没有,当您不再需要更新位置时,调用stopUpdatingLocation可能会获得更大的收益。 随后,您甚至无法访问didUpdateToLocation,因为您不再获取新的位置数据。
您现在使用的方法, -locationManager:didUpdateToLocation:fromLocation
是对用户位置执行任何操作的最佳位置。 不过,我会做一些与你不同的事情。
首先,您接受第一个位置更新是最好的。 您可能已经要求一定的准确性,但要求它并不意味着该方法的newLocation
是最好的。 通常情况下,从过去的某个时间开始,您将获得非常低的准确度或缓存位置。 我要做的是检查新位置的年龄和准确性,并且只有在它放大的时候才能进行。
我要做的另一件事是关闭位置更新,无论是在准确更新时,还是在更新开始后30秒。 设置一个计时器将其关闭,当您将其关闭时,设置一个较长的计时器将其重新打开并再次检查。
最后,确保您已正确实现-locationManager:didFailWithError:
适用于所有情况。 它总是在您提交应用程序时测试的内容之一。 如果它没有正常失败(例如,在飞行模式下),它可能会被拒绝。
搜索Stack Overflow以获取执行这些操作的技术和代码。
您可以随时初始化并开始获取位置更新。 每当收到新位置时,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];
您可以创建一个“初始”委托实现,可以在缩放到位置后取消注册,并注册现在不需要整个缩放的“普通”委托,如果有的话。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.