2014-10-22 68 views
1

我試圖跟蹤用戶的路線和繪製線的路線,但addOverlay只給我正確的點,但每個點之間沒有連接。MKPolyline只繪製點而不是線

-(void)viewWillAppear:(BOOL)animated{ 
    self.trackPointArray = [[NSMutableArray alloc] init]; 
} 

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(CLLocation *)userLocation 
{ 
    [self.trackPointArray addObject:userLocation]; 

    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 1000, 1000); 
    [self.myMapView setRegion:[self.myMapView regionThatFits:region] animated:YES]; 

    NSInteger stepsNumber = self.trackPointArray.count; 

    CLLocationCoordinate2D coordinates[stepsNumber]; 
    for (NSInteger index = 0; index < stepsNumber; index++) { 
     CLLocation *location = [self.trackPointArray objectAtIndex:index]; 
     coordinates[index] = [location coordinate]; 
    } 
    MKPolyline *polyLine = [MKPolyline polylineWithCoordinates:coordinates count:stepsNumber]; 
    [self.myMapView addOverlay:polyLine]; 
} 


- (MKOverlayRenderer *)mapView:(MKMapView *)myMapView rendererForOverlay:(id<MKOverlay>)overlay 
{ 
    MKPolylineRenderer *polylineRenderer = [[MKPolylineRenderer alloc] initWithOverlay:overlay]; 
    polylineRenderer.lineWidth = 4.0f; 
    polylineRenderer.strokeColor = [UIColor redColor]; 
    return polylineRenderer; 
} 

回答

1

userLocation對象地圖視圖傳遞給didUpdateUserLocation委託方法是每次的相同的對象。

對象內部的coordinate在每個時刻都可能不同,但對委託方法的每次調用始終指向相同的容器對象。

具體來說,它總是指向地圖視圖的userLocation屬性指向(mapView.userLocation)的相同對象。你可以看到這個,如果你NSLoguserLocationmapView.userLocation並且注意它們的內存地址每次都是一樣的。


出於這個原因,當代碼執行此:

[self.trackPointArray addObject:userLocation]; 

它只是增加了相同的對象參照陣列多次。

稍後,當代碼遍歷trackPointArray陣列,每個調用[location coordinate]返回相同的座標每次因爲location總是指向同一對象(mapView.userLocation)和座標循環期間不改變。

因此,每次調用委託方法時,將使用N個座標(完全相同)創建折線,最終繪製一個「點」。

您看到多個點的原因是因爲代碼沒有刪除以前的疊加層。


要解決這一切,一個簡單的方法是要添加更新後的座標,每次創建新的CLLocation實例:

CLLocation *tpLocation = [[CLLocation alloc] 
          initWithLatitude:userLocation.coordinate.latitude 
          longitude:userLocation.coordinate.longitude]; 
[self.trackPointArray addObject:tpLocation]; 

此外,添加更新之前,您應該刪除以前的疊加線。如果您不這樣做,您將不會注意到前面的行,但他們會在那裏使用內存和性能:

[self.myMapView removeOverlays:self.myMapView.overlays]; 
[self.myMapView addOverlay:polyLine]; 
+0

謝謝!這完美地解決了我的問題。 – 2014-10-22 23:13:42