iPhone开发之绘制地图线路


地图应用经常会涉及到线路的绘制问题,ios下可以使用MKMapView进行地图开发,使用MKOverlayView进行线路的绘制。

使用MKMapView添加MKMap.framework 和CoreLocation.framework并导入MapKit.h头文件。

新建一个基于视图的工程,修改头文件:

  1. //   
  2. //  CloViewController.h   
  3. //  LocationMapTest   
  4. //   
  5. //  Created by Cloay on 12-6-18.   
  6. //  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.   
  7. //   
  8.   
  9. #import <UIKit/UIKit.h>   
  10. #import <MapKit/MapKit.h>   
  11. #import "CloMKAnnotation.h"   
  12. @interface CloViewController : UIViewController<CLLocationManagerDelegate, MKMapViewDelegate, UIActionSheetDelegate>{  
  13.     MKMapView *cloMapView;  
  14.     MKPolyline *routeLine;  
  15. }  
  16.   
  17. @property (nonatomic, strong)  NSMutableArray *locations;  
  18. @end  

修改实现代码,在.m中添加如下代码:
  1. //   
  2. //  CloViewController.m   
  3. //  LocationMapTest   
  4. //   
  5. //  Created by Cloay on 12-6-18.   
  6. //  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.   
  7. //   
  8.   
  9. #import "CloViewController.h"   
  10.   
  11. @interface CloViewController ()  
  12.   
  13. @end  
  14.   
  15. @implementation CloViewController  
  16. @synthesize locations;  
  17.   
  18. - (void)viewDidLoad  
  19. {  
  20.     [super viewDidLoad];  
  21.     // Do any additional setup after loading the view, typically from a nib.   
  22.     cloMapView = [[MKMapView alloc] initWithFrame:[self.view bounds]];  
  23.     [cloMapView setMapType:MKMapTypeHybrid];  //设置地图类型 地图/卫星/两者结合   
  24.     [cloMapView setShowSUSErLocation:YES];      //显示当前位置   
  25.     [cloMapView setDelegate:self];  
  26.       
  27.     CLLocationManager *locationManager = [[CLLocationManager alloc] init];  
  28.     //设置CLLocationManager实例委托和精度   
  29.     [locationManager setDelegate:self];  
  30.     [locationManager setDesiredAccuracy:kCLLocationAccuracyBest];  
  31.     //设置距离筛选器,表示至少移动100米才通知委托更新   
  32.     [locationManager setDistanceFilter:100.f];  
  33.     //启动更新请求   
  34. //    [locationManager startUpdatingLocation];   
  35.       
  36.     locations = [[NSMutableArray alloc] init];  
  37.     float latitude = 39.8127;    //维度   
  38.     float longitude = 116.2967;  //经度   
  39.     for (int i = 0; i < 10; i++) {  
  40.           
  41.         [locations addObject:[NSString stringWithFormat:@"%f,%f", latitude + 0.01*i, longitude + 0.01*i]];  
  42. //            NSLog(@"locations:%i",locations.count);   
  43.     }  
  44.       
  45.     //地图初始   
  46.     CLLocationCoordinate2D coords;  
  47.     coords.latitude = 39.9127;  
  48.     coords.longitude = 116.3967;  
  49.     float zoomlevel = 0.22;  
  50.     MKCoordinateRegion region = MKCoordinateRegionMake(coords, MKCoordinateSpanMake(zoomlevel, zoomlevel));  
  51.     [cloMapView setRegion:[cloMapView regionThatFits:region] animated:YES];  
  52.       
  53.     [cloMapView addOverlay:[self makePolylineWithLocations:locations]];  
  54.     [self.view addSubview:cloMapView];  
  55.       
  56. }  
  57.   
  58. - (void)viewDidUnload  
  59. {  
  60.     [super viewDidUnload];  
  61.     // Release any retained subviews of the main view.   
  62.     cloMapView = nil;  
  63. }  
  64.   
  65. - (void)dealloc{  
  66.     [cloMapView release];  
  67.     [super dealloc];  
  68. }  
  69.   
  70. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation  
  71. {  
  72.     return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);  
  73. }  
  74.   
  75.   
  76. //显示菜单选项   
  77. - (void)showActionSheet :(id)sender{  
  78.     UIActionSheet * actionSheet = [[UIActionSheet alloc] initWithTitle:nil   
  79.                                                               delegate:self   
  80.                                                      cancelButtonTitle:@"取消"  
  81.                                                 destructiveButtonTitle:@"添加足迹"  
  82.                                                      otherButtonTitles:@"分享",@"详细",@"删除", nil];  
  83.     [actionSheet setDelegate:self];  
  84.     [actionSheet showInView:self.view];  
  85.     [actionSheet release];  
  86. }  
  87.   
  88. //根据坐标点生成线路   
  89. - (MKPolyline *)makePolylineWithLocations:(NSMutableArray *)newLocations{  
  90.     MKMapPoint *pointArray = malloc(sizeof(CLLocationCoordinate2D)* newLocations.count);  
  91.     for(int i = 0; i < newLocations.count; i++)    
  92.     {    
  93.         // break the string down even further to latitude and longitude fields.      
  94.         NSString* currentPointString = [newLocations objectAtIndex:i];    
  95.         NSArray* latLonArr = [currentPointString componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@","]];  
  96.         CLLocationDegrees latitude  = [[latLonArr objectAtIndex:0] doubleValue];    
  97.         //        NSLog(@"latitude-> %f", latitude);   
  98.         CLLocationDegrees longitude = [[latLonArr objectAtIndex:1] doubleValue];    
  99.         CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(latitude, longitude);    
  100.         //        NSLog(@"point-> %f", point.x);   
  101.           
  102.         if (i == 0 || i == locations.count - 1) {//这里只添加起点和终点作为测试   
  103.             CloMKAnnotation *ann = [[CloMKAnnotation alloc] init];  
  104.             [ann setCoordinate:coordinate];  
  105.             [ann setTitle:[NSString stringWithFormat:@"纬度:%f", latitude]];  
  106.             [ann setSubtitle:[NSString stringWithFormat:@"经度:%f", longitude]];  
  107.             [cloMapView addAnnotation:ann];  
  108.         }  
  109.         pointArray[i] = MKMapPointForCoordinate(coordinate);  
  110.     }    
  111.       
  112.     routeLine = [MKPolyline polylineWithPoints:pointArray count:newLocations.count];  
  113.     free(pointArray);  
  114.     return routeLine;  
  115. }  
  116. #pragma mark-   
  117. #pragma CLLocationManager delegate method   
  118. //位置变化后会调用   
  119. - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{  
  120.     //可在此处更新用户位置信息   
  121. //    cloMapView.userLocation   
  122.     NSLog(@"oldLocation:%@", [oldLocation description]);  
  123.     NSLog(@"newLocation:%@", [newLocation description]);  
  124.     NSLog(@"distance:%@", [newLocation distanceFromLocation:oldLocation]);  
  125.     //位置变化添加新位置点   
  126.     [locations addObject:[NSString stringWithFormat:@"%f,%f", newLocation.coordinate.latitude, newLocation.coordinate.longitude]];  
  127.     //删除进线路,更新新轨迹   
  128.     [cloMapView removeOverlay:routeLine];  
  129.     [cloMapView addOverlay:[self makePolylineWithLocations:locations]];  
  130.   
  131. }  
  132.   
  133. #pragma MKMapView delegate method   
  134. //添加坐标点大头针   
  135. - (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{  
  136.     if (![annotation isKindOfClass:[CloMKAnnotation class]]) {  
  137.         return nil;  
  138.     }  
  139.     static NSString *identifier = @"Annotation";  
  140.     MKPinAnnotationView *pinAnnotationView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:identifier];  
  141.     if (pinAnnotationView == nil) {  
  142.         pinAnnotationView = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifier] autorelease];  
  143.     }  
  144.     pinAnnotationView.animatesDrop = YES;  
  145.     pinAnnotationView.canShowCallout = YES;  
  146.     pinAnnotationView.draggable = YES;  
  147.     UIButton *detailBtn = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];  
  148.     [detailBtn addTarget:self action:@selector(showActionSheet:) forControlEvents:UIControlEventTouchUpInside];  
  149.     pinAnnotationView.rightCalloutAccessoryView = detailBtn;  
  150.       
  151.     return pinAnnotationView;  
  152. }  
  153.   
  154. - (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view didChangeDragState:(MKAnnotationViewDragState)newState fromOldState:(MKAnnotationViewDragState)oldState{  
  155.       
  156. }  
  157.   
  158. //画线   
  159. - (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id<MKOverlay>)overlay{  
  160.     NSLog(@"return overLayView...");  
  161.     if ([overlay isKindOfClass:[MKPolyline class]]) {  
  162.         MKPolylineView *routeLineView = [[[MKPolylineView alloc] initWithPolyline:routeLine] autorelease];  
  163.         routeLineView.strokeColor = [UIColor blueColor];  
  164.         routeLineView.lineWidth = 3;  
  165.         return routeLineView;  
  166.     }  
  167.     return nil;  
  168. }  
  169.   
  170. @end  
这里主要是为了测试,初始时 locations坐标点自定义的,实际中是根据用户的位置动态生成的一系列坐标点。具体可在
  1. - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation  
函数中实现,如上代码。

另外用户的实时位置可用

  1. cloMapView.userLocation = newLocation进行设置,然后显示在地图上。  
效果图如下:

相关内容