ios地图两点间连线,移动后最后一个点总是连接00点求大神解答
发布网友
发布时间:2022-05-06 06:39
我来回答
共1个回答
热心网友
时间:2022-06-28 22:27
当我们获取了一组地理位置后,可能会想要在地图上绘制这组地理位置信息所包含的路线。
MKMapView提供了addOverlay功能(以及addAnnotation),让我们可以在地图上放一层遮罩。如果要放一组遮罩,可以用addOverlays。
[cpp] view plain copy
#pragma mark -
- (void)drawLineWithLocationArray:(NSArray *)locationArray
{
int pointCount = [locationArray count];
CLLocationCoordinate2D *coordinateArray = (CLLocationCoordinate2D *)malloc(pointCount * sizeof(CLLocationCoordinate2D));
for (int i = 0; i < pointCount; ++i) {
CLLocation *location = [locationArray objectAtIndex:i];
coordinateArray[i] = [location coordinate];
}
self.routeLine = [MKPolyline polylineWithCoordinates:coordinateArray count:pointCount];
[self.mapView setVisibleMapRect:[self.routeLine boundingMapRect]];
[self.mapView addOverlay:self.routeLine];
free(coordinateArray);
coordinateArray = NULL;
}
MKPolyLine为我们提供了方便绘制多条线段的功能,它实现了MKOverlay协议,但并不能作为遮罩。我们需要实现相应的遮罩代理方法:
[cpp] view plain copy
#pragma mark - MKMapViewDelegate
- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id<MKOverlay>)overlay
{
if(overlay == self.routeLine) {
if(nil == self.routeLineView) {
self.routeLineView = [[[MKPolylineView alloc] initWithPolyline:self.routeLine] autorelease];
self.routeLineView.fillColor = [UIColor redColor];
self.routeLineView.strokeColor = [UIColor redColor];
self.routeLineView.lineWidth = 5;
}
return self.routeLineView;
}
return nil;
}
下面是我的测试代码,用北京的经纬度和杭州的经纬度画线:
[cpp] view plain copy
- (void)drawTestLine
{
CLLocation *location0 = [[CLLocation alloc] initWithLatitude:39.954245 longitude:116.312455];
CLLocation *location1 = [[CLLocation alloc] initWithLatitude:30.247871 longitude:120.127683];
NSArray *array = [NSArray arrayWithObjects:location0, location1, nil];
[self drawLineWithLocationArray:array];
}