目标 c - MKMapView 中用户位置的中心区域



>我很困惑。我有一个MKMapView,在viewDidLoad方法中,我做了:

- (void)viewDidLoad {
    mainDelegate = (PublicArtOmahaAppDelegate*)[[UIApplication sharedApplication]delegate]; 
    XMLController  *myXMLController = [[XMLController alloc] init]; 
    [myXMLController parse];
    mapView.showsUserLocation = YES;
    [self gotoLocation];
    // add annotations to map
    [self.mapView addAnnotations:mainDelegate.mapAnnotations];
    [myXMLController release];
}

[自转到位置]调用:

- (void)gotoLocation
{
    MKCoordinateRegion newRegion;
    CLLocation *userLocation = mapView.userLocation.location;
    float latitude = userLocation.coordinate.latitude;
    float longitude = userLocation.coordinate.latitude;
    newRegion.center.latitude = latitude;
    newRegion.center.longitude = longitude;
    [self.mapView setRegion:newRegion animated:YES];
}

所以我认为这应该在 mapView 加载时将地图集中在用户的位置上,我还计划在屏幕上实现一个按钮,该按钮将再次手动调用 gotoLocation 以在需要时更新用户的位置。

但。。。当我在设备上运行该应用程序时,它会加载以非洲西部一片海洋为中心的地图,该地图显然是纬度和长度 0,0。我觉得奇怪的是,当我缩放回我的真实位置时,它正确地将我的位置作为注释放置。所以我想我在gotoLocation中设置用户位置的方式有问题吗?有人注意到我做错了什么吗?

来自MKUserLocation文档:

位置

设备的当前位置。(只读)

@property (readonly, nonatomic) CLLocation *location

讨论

如果地图视图当前未显示用户位置或尚未确定用户的位置,则此属性包含 nil。

MKMapView(或CLLocationManager)需要几秒钟才能修复用户的位置,并且可能需要几次尝试才能获得相对准确的修复。最好的办法可能是创建一个CLLocationManager对象,为其分配一个委托,然后在触发locationManager:didUpdateToLocation:fromLocation:方法时缩放地图。

您也应该为区域设置span。将其设置为某个任意值,例如 latitudeDelta = 0.01(对于 latitudeDelta 也是如此)。

此外,请从– locationManager:didUpdateToLocation:fromLocation:内部呼叫gotoLocation(如果您使用的是位置管理器)。这样,仅当您具有有效的用户位置时,才会调用它。

最新更新