我使用MKPolyline在现有位置和用户当前位置之间画一条线。 当视图出现时一切正常并且线条正确,但是当用户的当前位置发生变化时,我希望两个位置之间的线也更新。 这是我的代码
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
self.currentLatitude = userLocation.coordinate.latitude;
self.currentLongitude = userLocation.coordinate.longitude;
[self addObserver:self forKeyPath:@"self.currentLatitude" options:NSKeyValueObservingOptionNew context:nil];
[self addObserver:self forKeyPath:@"self.currentLongitude" options:NSKeyValueObservingOptionNew context:nil];
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
// Remove the old overlay
[self.mapView removeOverlay:self.routeLine];
if ([keyPath isEqualToString:@"self.currentLatitude"])
{
self.newCurrentLatitude = [[change valueForKey:@"new"] floatValue];
}
if ([keyPath isEqualToString:@"self.currentLongitude"])
{
self.newCurrentLongitude = [[change valueForKey:@"new"] floatValue];
}
// Draw line between user location and location that had choosen in table
CLLocationCoordinate2D coordinateArray[2];
coordinateArray[0] = CLLocationCoordinate2DMake(self.newCurrentLatitude, self.newCurrentLongitude);
coordinateArray[1] = CLLocationCoordinate2DMake(self.latitudeOfPlaceFromTable, self.longitudeOfPlaceFromTable);
self.routeLine = [MKPolyline polylineWithCoordinates:coordinateArray count:2];
[self.mapView setVisibleMapRect:[self.routeLine boundingMapRect]];
[self.mapView addOverlay:self.routeLine];
}
有人可以帮助我吗?感谢
答案 0 :(得分:0)
MKPolyline是不可变的,因此您需要使用removeOverlay方法删除叠加层,并像以前一样使用新的折线添加新的叠加层。