iOS使用CLLocation& MapView一起获取坐标并更新地图

时间:2014-01-14 14:53:01

标签: ios mapkit core-location

我有一个需要做两件事的应用程序;

  1. 获取当前位置
  2. 将Mapview更新到该位置
  3. 我正在使用以下代码;

    -(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation     *)newLocation fromLocation:(CLLocation *)oldLocation
    {
        CLLocation *currentLocation = newLocation;
        if (currentLocation != nil) {
        NSLog(@"%.8f", currentLocation.coordinate.longitude);
        NSLog(@"%.8f", currentLocation.coordinate.latitude);
        NSLog(@"%f", currentLocation.speed);
    
        MKCoordinateRegion mapRegion;
        mapRegion.center.longitude = currentLocation.coordinate.longitude;
        mapRegion.center.latitude = currentLocation.coordinate.latitude;
        mapRegion.span.latitudeDelta = 0.03;
        mapRegion.span.longitudeDelta = 0.03;
        [_mapView setRegion:mapRegion animated: YES];
    }
    }
    

    除了一件事,一切都按照我的预期发生。当MapView区域更新时,MAP会移动,但PIN不会移动。最终,用户引脚不在屏幕上,因为地图与坐标一致。

    非常感谢任何帮助。

1 个答案:

答案 0 :(得分:4)

在下面设置_mapView区域的位置,您还应该使用currentLocation创建一个新的注释并将其添加到_mapView。代码看起来应该是,

-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation     *)newLocation fromLocation:(CLLocation *)oldLocation
{
    CLLocation *currentLocation = newLocation;
    if (currentLocation != nil) {
    NSLog(@"%.8f", currentLocation.coordinate.longitude);
    NSLog(@"%.8f", currentLocation.coordinate.latitude);
    NSLog(@"%f", currentLocation.speed);

    MKCoordinateRegion mapRegion;
    mapRegion.center.longitude = currentLocation.coordinate.longitude;
    mapRegion.center.latitude = currentLocation.coordinate.latitude;
    mapRegion.span.latitudeDelta = 0.03;
    mapRegion.span.longitudeDelta = 0.03;
    [_mapView setRegion:mapRegion animated: YES];

    MyAnnotation *ant = [[MyAnnotation alloc] initWithCoordinate:currentLocation.coordinate];
    [_mapView addAnnotation:ant];
}