2013-05-08 102 views
0

我使用下面的代碼來計算我的應用用戶的位置和附近位置(註釋)之間的距離。當我嘗試在標籤中顯示「Distance Away」作爲文本時,它會一直說計算出的距離爲0.爲什麼?計算用戶與附近地點之間的距離,計算出的距離一直顯示爲0?

*請注意,我的表格使用放置在我的MapView上的座標來確定距離。

下面是我使用來計算到附近的位置

MapViewController.m

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { 

    for (MapViewAnnotation *annotation in self.mapView.annotations) { 
CLLocationCoordinate2D coord = [annotation coordinate]; 
CLLocation *annotationLocation = [[CLLocation alloc] initWithLatitude:coord.latitude longitude:coord.longitude]; 
annotation.distance = [newLocation distanceFromLocation:annotationLocation]; 



    } 

在這裏,從我的用戶的距離代碼的我用來顯示calculatedDistance位在一個標籤(位於我的自定義單元格中以顯示在桌面視圖中):

ViewController.m

cell.distanceLabel.text = [NSString stringWithFormat:@"%f m.", calculatedDistance]; 

任何幫助將不勝感激!

回答

1
for (MapViewAnnotation *annotation in self.mapView.annotations) { 
    CLLocationCoordinate2D coord = [annotation coordinate]; 
    CLLocation *userLocation = [[CLLocation alloc] initWithLatitude:coord.latitude longitude:coord.longitude]; 

這不是用戶的位置,這是註釋的位置。但奇怪的變量名旁白:

CLLocationDistance calculatedDistance = [userLocation distanceFromLocation:userLocation]; 

從一個位置之間的距離,以自身爲0 該行可能是一個錯誤。也許你的意思

CLLocationDistance calculatedDistance = [newLocation distanceFromLocation:userLocation]; 

這將返回用戶的新位置和(名不副實)標註的位置之間的距離 - 你想大概是什麼。當然,你實際上是在距離自我計算上面的線上計算出來的,然後把它扔掉兩行。

tl; dr

扔掉最後兩行,它們沒用。

+0

我放棄了最後兩行,並改變了我的變量名(lol)。查看上面更新的代碼。那是我應該結束的嗎?我不需要定義calculateDistance嗎?感謝您的幫助,順便說一句! – 2013-05-08 01:06:41

+0

只需將它(距離)拉出顯示代碼中的註釋或其他東西。 (此外,單個變量'calculateDistance'不適合保存多個距離(因爲它被要求在'for'循環中做)。) – michaelb958 2013-05-08 01:13:21

+0

好吧,我現在完全看到爲什麼我最後兩行沒用,哈哈。你能告訴我w/code如何看起來?我有點困惑!謝謝 :) – 2013-05-14 19:21:53