2012-10-16 36 views
3

我有一個CLLocation對象的數組,我從文件中解析出來。我想模擬用戶沿着這條路線移動,我已經實現了這一點:試圖模擬MapView中的路由

for (CLLocation *loc in simulatedLocs) { 
      [self moveUser:loc]; 
      sleep(1); 
     } 

這就是所謂的循環方法:在

- (void)moveUser:(CLLocation*)newLoc 
{ 
    CLLocationCoordinate2D coords; 
    coords.latitude = newLoc.coordinate.latitude; 
    coords.longitude = newLoc.coordinate.longitude; 
    CustomAnnotation *annotation = [[CustomAnnotation alloc] initWithCoordinate:coords]; 
    annotation.title = @"User"; 

    // To remove the previous location icon 
    NSArray *existingpoints = self.mapView.annotations; 
    if ([existingpoints count] > 0) { 
     for (CustomAnnotation *annotation in existingpoints) { 
      if ([annotation.title isEqualToString:@"User"]) { 
       [self.mapView removeAnnotation:annotation]; 
       break; 
      } 
     } 
    } 

    MKCoordinateRegion region = { coords, {0.1, 0.1} }; 
    [self.mapView setRegion:region animated:NO]; 
    [self.mapView addAnnotation: annotation]; 
    [self.mapView setCenterCoordinate:newLoc.coordinate animated:NO]; 
} 

但只有最後一個位置在運行iPhone模擬器時,數組及其區域顯示在mapView中。我想模擬用戶每1秒「移動」,我怎麼能這樣做?

謝謝!

+2

不要像那樣使用'sleep'。 –

回答

1

在每次迭代中一次循環遍歷所有位置並使用sleep將不起作用,因爲UI將被阻塞,直到循環處理完成。

相反,安排moveUser方法爲每個位置單獨調用,以便UI在整個序列中不被阻塞。調度可以使用NSTimer或可能更簡單和更靈活的方法完成,例如performSelector:withObject:afterDelay:方法。

保持一個索引ivar以跟蹤哪個位置移動到每次調用moveUser時。

例如:

//instead of the loop, initialize and begin the first move... 
slIndex = 0; //this is an int ivar indicating which location to move to next 
[self manageUserMove]; //a helper method 

-(void)manageUserMove 
{ 
    CLLocation *newLoc = [simulatedLocs objectAtIndex:slIndex]; 

    [self moveUser:newLoc]; 

    if (slIndex < (simulatedLocs.count-1)) 
    { 
     slIndex++; 
     [self performSelector:@selector(manageUserMove) withObject:nil afterDelay:1.0]; 
    } 
} 

現有moveUser:方法不必被改變。


需要注意的是用戶體驗和代碼可如果不是刪除,每次重新添加註釋,你在開始一次添加它,只是在每一個「移動」改變其coordinate屬性進行簡化。

+0

謝謝,我最終決定使用'performSelector'方法,並更改我的'moveUser'方法來更新座標而不是刪除和添加新的註釋。現在它像我想要的那樣工作,謝謝:) 並感謝你們所有的回覆! –

0

您不應該使用MKAnnotation,但MKPolyline。檢查documentation。另外,請查看2010年的WWDC MapKit視頻。它有一個可變MKPolyline的例子。

+0

我正在使用註釋,因爲我想以類似的方式爲當前位置繪製一個圖標,默認情況下會顯示用戶位置的藍色點...我不想繪製完整路線,我只想繪製一步一步地繪製位置,就好像用戶正在步行 –

0

你的問題是,它的睡眠for循環,阻止主線程,直到循環結束。這會凍結整個用戶界面,包括您在moveUser中所做的任何更改。

而不是for循環,使用NSTimer,每秒觸發一次,每做一步。

或者,爲了獲得更平滑的效果,可以設置一個動畫,沿着預定義的路徑移動註釋的位置。