【问题标题】:iPhone Development - CLLocationManager vs. MapKitiPhone 开发 - CLLocationManager 与 MapKit
【发布时间】:2023-11-28 09:56:01
【问题描述】:

如果我想在地图上显示 userLocation,同时记录用户的位置,向 userLocation.location 添加观察者并记录位置是否是个好主意,或者我是否仍应使用 CLLocationManager 记录用户location 并使用 mapView.showUserLocation 显示用户的当前位置(蓝色指示器)?我想显示 MapKit API 支持的默认蓝色指示器。

另外,这里有一个粗略的示例代码:

- (void)viewDidLoad {
    ...

    locationManager = [[CLLocationManager alloc] init]; 
    locationManager.desiredAccuracy = kCLLocationAccuracyBest; 
    locationManager.distanceFilter = DISTANCE_FILTER_VALUE;
    locationManager.delegate = self; 
    [locationManager startUpdatingLocation];

    myMapView.showUserLocation = YES;
    [myMapView addObserver:self forKeyPath:@"userLocation.location" options:0 context:nil];

    ...
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    // Record the location information
    // ...
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { 
    NSLog(@"%s begins.", __FUNCTION__);

    // Make sure that the location returned has the desired accuracy
    if (newLocation.horizontalAccuracy <= manager.desiredAccuracy)
        return;

    // Record the location information
    // ...
}

在幕后,我认为 MKMapView 还使用 CLLocationManager 来获取用户的当前位置?那么,这是否会产生任何问题,因为我相信 CLLocationManager 和 MapView 都会尝试使用相同的位置服务?是否存在任何冲突以及缺乏准确/必需或当前的数据?

【问题讨论】:

    标签: iphone mapkit mkmapview cllocationmanager showuserlocation


    【解决方案1】:

    查看SO entry:CLLocationManager 在其所有实例中使用相同的数据,因此不存在冲突。

    【讨论】:

    • 但是如果我们将 showUserLocation 设置为 TRUE 并在我们的自定义类中创建一个 CLLocationManager,我们实际上是在创建 CLLocationManager 的两个实例 - 一个由 MKMapView 使用,一个在您的自定义类中。谁将获得位置更新? userLocation.location 上的观察者还是 didUpdateLocation: 委托方法?如果我开始记录这两个位置,记录的位置会同步吗?
    • 显然,您可以拥有多个位置经理,他们会为您提供准确的信息。尽管 MapKit 也在底层使用 CLLocationManager,但创建 CLLocationManager 并将其与 MapKit 一起使用不会产生任何冲突。