我想在應用程序的一開始就使用corelocation來獲取初始位置。CLLocationManager distanceFromLocation:returns -1
我有委託方法:
-(void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
NSDate* eventDate = newLocation.timestamp;
NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
DLog(@"received location data from %f ago, lat/long - %+.6f, %+.6f\nold lat/long %+.6f, %+.6f\nhorizontal accuracy is %f",
howRecent, newLocation.coordinate.latitude, newLocation.coordinate.longitude,
oldLocation.coordinate.latitude, oldLocation.coordinate.longitude,
newLocation.horizontalAccuracy);
// check if new update is significantly different from old one. If it is, then reverse-geocode.
if ([newLocation respondsToSelector:@selector(distanceFromLocation:)]) {
DLog(@"distance from old to new location - %f", [newLocation distanceFromLocation:oldLocation]);
if ([newLocation distanceFromLocation:oldLocation] < 1000) {
// reverse geocode please
[self stopLocationManager];
}
}
else if ([newLocation respondsToSelector:@selector(getDistanceFrom:)]){
DLog(@"distance from old to new location - %f", [newLocation getDistanceFrom:oldLocation]);
if ([newLocation getDistanceFrom:oldLocation] < 1000) {
// reverse geocode please
[self stopLocationManager];
}
}
}
這裏的日誌輸出:
... -[AppHelper locationManager:didUpdateToLocation:fromLocation:] received location data from -13.261873 ago, lat/long - +37.705413, -121.866296
old lat/long +0.000000, +0.000000
horizontal accuracy is 1982.000000
... -[AppHelper locationManager:didUpdateToLocation:fromLocation:] distance from old to new location - -1.000000
知道爲什麼從newlocation到的oldlocation初始距離計算(0,0),產生-1結果?
錯誤是誤導性的,因爲0,0實際上是一個有效的位置。我檢查了谷歌地圖,這有點西非大陸:(所以,我試圖忽視,如果經/緯度是等於0,但是這沒」如果(!(oldLocation.coordinate.latitude == 0.0 && oldLocation.coordinate.longitude == 0.0)總是返回零哈哈。無論如何,當你調用nil對象的屬性時,似乎是錯誤的。我認爲如果oldlocation實際上它是一個0,0的有效對象,計算工作正常。 – 2011-03-12 12:54:56
是的,但你似乎不太可能在lat/long +0.000000,+0.000000和lat/long - + 37.705413,-121.866296之間移動,而沒有得到任何更新在這之間,所以我仍然認爲忽略第一個距離是要走的路。:P – 2011-03-12 12:59:31
如果你調用一個無對象的方法,它總是返回0. – 2011-03-12 13:00:55