在iPhone上更新/缩放到当前位置

时间:2010-11-10 23:15:40

标签: iphone mkmapview

好的,所以当我点击当前位置按钮时,我试图获得与iPhone地图应用程序相同的放大/位置更新功能。我使用的是从herehere(Brad Smith的帖子中的代码)中找到的代码来完成大部分工作。因此,我真正需要做的就是将地图置于更新的当前位置周围,并在每次更新时进一步放大。

现在我在测试centerCoord是否为null时遇到了一些困难。正如您从结果中看到的那样(下面列出),它因某些原因而崩溃,我无法弄清楚。以下是相关代码:

- (void) showCurrentLocationButtonTapped {
    NSLog(@"Showing current location.");

    locController = [[LocationController alloc] init];

    [mapView setShowsUserLocation:YES];

    zoomTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(zoomToCurrentLocation) userInfo:nil repeats:YES];

}

- (void) zoomToCurrentLocation {
    CLLocationCoordinate2D centerCoord = self.locController.currentLocation.coordinate;
    NSLog(@"Checking if loc controller is null");
    if (!self.locController) {
        NSLog(@"centerCoord is null!");
    }
    NSLog(@"centerCoord: %@",centerCoord);
    [mapView setCenterCoordinate:centerCoord zoomLevel:7 animated:YES];
}

这是控制台输出:

2010-11-10 14:56:11.002 App Name[5278:207] Showing current location.
2010-11-10 14:56:11.504 App Name[5278:207] Checking if loc controller is null
2010-11-10 14:56:11.505 App Name[5278:207] centerCoord: (null)
2010-11-10 14:56:12.004 App Name[5278:207] Checking if loc controller is null
2010-11-10 14:56:12.004 App Name[5278:207] centerCoord: (null)
2010-11-10 14:56:12.504 App Name[5278:207] Checking if loc controller is null

我知道我没有测试centerCoord的null-ness,但如果我这样做:

if (!centerCoord) {

我在该行上收到错误消息:

MapViewController.m:55: error: wrong type argument to unary exclamation mark

2 个答案:

答案 0 :(得分:2)

以下是您需要做的事情:

首先,检查是否启用了位置服务:

if ([CLLocationManager locationServicesEnabled])
    [self findUserLocation];

然后在findUserLocation方法中,实例化你的CLLocationManager并开始接收更新:

- (void)findUserLocation
{
    CLLocationManager *locationManager_ = [[CLLocationManager alloc] init];
    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracy{ChooseYourOptionHere};
    [locationManager startUpdatingLocation];
}

最后,实现此委托方法,每次收到更新时都会调用该方法。根据您所需的准确度(如上所述)检查当前位置的准确性,如果您满意,请将地图置于中心位置并且不要忘记阻止位置管理员接收更新:

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    if ([newLocation horizontalAccuracy] < [manager desiredAccuracy])
    {
        // Accuracy is good enough, zoom to current location
        [manager stopUpdatingLocation];
    }
// else keep trying...
}

答案 1 :(得分:0)

位置控制器可能需要时间来更新您的位置 尝试将您的计时器设置为30秒,看看会发生什么。