iOS - 在应用启动时缩放到当前用户位置

时间:2012-02-25 23:03:17

标签: iphone ios mkmapview core-location

我想在启动时将地图缩放到当前用户位置。我试图在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是相关的,所以我想删除它,出于性能原因。

4 个答案:

答案 0 :(得分:5)

我非常怀疑一个失败的if语句是你需要担心的性能。

您是否经常需要定位服务?如果没有,当您不再需要更新位置时,调用stopUpdatingLocation可能会获得更大的收益。随后,您甚至无法访问didUpdateToLocation,因为您不再获取新的位置数据。

答案 1 :(得分:2)

您现在使用的方法-locationManager:didUpdateToLocation:fromLocation是处理用户位置的最佳位置。但是我会做一些与你不同的事情。

首先,您接受第一个位置更新是最好的。您可能已经要求一定的准确性,但要求它并不意味着该方法的newLocation是最好的。通常情况下,从过去的某个时间开始,您将获得非常低的准确度或缓存位置。我要做的是检查新位置的年龄和准确度,并且只有在它放大时才会有效。

我要做的另一件事是关闭位置更新,无论是在准确度更高的更新中,还是在更新开始后30秒。设置一个计时器将其关闭,当你关闭它时,设置一个更长的计时器将其重新打开并再次检查。

最后,请确保您已针对所有情况正确实施-locationManager:didFailWithError:。它总是在您提交应用程序时测试的内容之一。如果它没有正常失败(例如,在飞行模式下),它可能会被拒绝。

搜索Stack Overflow以获取执行这些操作的技术和代码。

答案 2 :(得分:2)

您可以随时初始化并开始获取位置更新。只要收到新位置,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];

答案 3 :(得分:2)

您可以制作一个“初始”委托实现,您可以在缩放到位置后取消注册,并注册现在不需要整个缩放的“普通”委托,如果有的话。

相关问题