[英]MKMapView or CLLocationManger - to determine user's current location
有两个类可帮助您进行地图绘制和确定用户位置MKMapView
和CLLocationManager
。
MKMapView
有一个委托“ didUpdateUserLocation
”,它告诉用户当前的位置。 同时, CLLocationManger
有一个委托“ didUpdateToLocation
”,它也做同样的事情。
我的问题是何时使用MKMapView
和CLLocationManager
。 我可以从MKMapView
获取设备的当前位置,然后为什么以及何时应该使用CLLocationManager
? 我试图得到它,但我仍然不确定。
我认为您将MKMapView
属性showsUserLocation与CLLocationManager
混淆了。
为方便起见,MKMapView允许您简单地启用一个属性以在地图UI上向用户显示当前位置。 如果只需要向用户显示他们在地图上的位置,这将非常方便。
但是,显然还有许多其他用例,仅在地图上显示位置是不够的,这就是CLLocationManager
用武之地。
例如,考虑一个跑步/训练应用程序,其中需要记录用户位置才能计算跑步距离,甚至考虑我自己的一个应用程序中的示例,在该应用程序中我需要查找用户位置(经/纬度)来计算距离实时访问各个火车站,以识别最接近用户的位置。 在这些示例中,不需要MapView,因此使用LocationManager是正确的选择。
任何时候您需要以编程方式与用户位置进行交互,并且基本上不需要地图UI!
我更喜欢使用MKMapView内部使用的CLLocationManager,因此,如果不需要使用地图,只需使用位置管理器中的以下代码。
locationManager = [[CLLocationManager alloc] init];
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.delegate = self;
[locationManager startUpdatingLocation];
只是不要忘记将locationManager实例存储在类中的某个位置,并且您可以像这样实现委托。
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
NSLog(@"Error detecting location %@", error);
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
CLLocation* location = (CLLocation*)locations.lastObject;
NSLog(@"Longitude: %f, Latitude: %f", location.coordinate.longitude, location.coordinate.latitude);
}
编辑
您可以使用Apple的地理编码器根据用户的位置获取用户的地址
// Use Apple's Geocoder to figure the name of the place
CLGeocoder* geoCoder = [[CLGeocoder alloc] init];
[geoCoder reverseGeocodeLocation:location completionHandler: ^(NSArray* placemarks, NSError* error) {
if (error != nil) {
NSLog(@"Error in geo coder: %@", error);
}
else {
if (placemarks.count == 0) {
NSLog(@"The address couldn't be found");
}
else {
// Get nearby address
CLPlacemark* placemark = placemarks[0];
// Get the string address and store it
NSString* locatedAt = [[placemark.addressDictionary valueForKey:@"FormattedAddressLines"] componentsJoinedByString:@", "];
location.name = locatedAt;
NSLog(@"The address is: %@", locatedAt);
}
}
}];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.