简易绘制地图路线

论坛 期权论坛 脚本     
匿名技术用户   2020-12-22 18:26   711   0

当我们获取了一组地理位置后,可能会想要在地图上绘制这组地理位置信息所包含的路线。

MKMapView提供了addOverlay功能(以及addAnnotation),让我们可以在地图上放一层遮罩。如果要放一组遮罩,可以用addOverlays。

  1. #pragma mark -
  2. - (void)drawLineWithLocationArray:(NSArray *)locationArray
  3. {
  4. int pointCount = [locationArray count];
  5. CLLocationCoordinate2D *coordinateArray = (CLLocationCoordinate2D *)malloc(pointCount * sizeof(CLLocationCoordinate2D));
  6. for (int i = 0; i < pointCount; ++i) {
  7. CLLocation *location = [locationArray objectAtIndex:i];
  8. coordinateArray[i] = [location coordinate];
  9. }
  10. self.routeLine = [MKPolyline polylineWithCoordinates:coordinateArray count:pointCount];
  11. [self.mapView setVisibleMapRect:[self.routeLine boundingMapRect]];
  12. [self.mapView addOverlay:self.routeLine];
  13. free(coordinateArray);
  14. coordinateArray = NULL;
  15. }

MKPolyLine为我们提供了方便绘制多条线段的功能,它实现了MKOverlay协议,但并不能作为遮罩。我们需要实现相应的遮罩代理方法:

  1. #pragma mark - MKMapViewDelegate
  2. - (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id<MKOverlay>)overlay
  3. {
  4. if(overlay == self.routeLine) {
  5. if(nil == self.routeLineView) {
  6. self.routeLineView = [[[MKPolylineView alloc] initWithPolyline:self.routeLine] autorelease];
  7. self.routeLineView.fillColor = [UIColor redColor];
  8. self.routeLineView.strokeColor = [UIColor redColor];
  9. self.routeLineView.lineWidth = 5;
  10. }
  11. return self.routeLineView;
  12. }
  13. return nil;
  14. }

下面是我的测试代码,用北京的经纬度和杭州的经纬度画线:

  1. - (void)drawTestLine
  2. {
  3. CLLocation *location0 = [[CLLocation alloc] initWithLatitude:39.954245 longitude:116.312455];
  4. CLLocation *location1 = [[CLLocation alloc] initWithLatitude:30.247871 longitude:120.127683];
  5. NSArray *array = [NSArray arrayWithObjects:location0, location1, nil];
  6. [self drawLineWithLocationArray:array];
  7. }
分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP