热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

iPhone开发之绘制地图线路

nsitionalENhttp:www.w3.orgTRxhtml1DTDxhtml1-transitional.dtd
地图应用经常会涉及到线路的绘制问题,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    
  10. #import    
  11. #import "CloMKAnnotation.h"   
  12. @interface CloViewController : UIViewController{  
  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)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)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进行设置,然后显示在地图上。  
效果图如下:


推荐阅读
  • 学习SLAM的女生,很酷
    本文介绍了学习SLAM的女生的故事,她们选择SLAM作为研究方向,面临各种学习挑战,但坚持不懈,最终获得成功。文章鼓励未来想走科研道路的女生勇敢追求自己的梦想,同时提到了一位正在英国攻读硕士学位的女生与SLAM结缘的经历。 ... [详细]
  • 本文介绍了使用kotlin实现动画效果的方法,包括上下移动、放大缩小、旋转等功能。通过代码示例演示了如何使用ObjectAnimator和AnimatorSet来实现动画效果,并提供了实现抖动效果的代码。同时还介绍了如何使用translationY和translationX来实现上下和左右移动的效果。最后还提供了一个anim_small.xml文件的代码示例,可以用来实现放大缩小的效果。 ... [详细]
  • android listview OnItemClickListener失效原因
    最近在做listview时发现OnItemClickListener失效的问题,经过查找发现是因为button的原因。不仅listitem中存在button会影响OnItemClickListener事件的失效,还会导致单击后listview每个item的背景改变,使得item中的所有有关焦点的事件都失效。本文给出了一个范例来说明这种情况,并提供了解决方法。 ... [详细]
  • Centos7.6安装Gitlab教程及注意事项
    本文介绍了在Centos7.6系统下安装Gitlab的详细教程,并提供了一些注意事项。教程包括查看系统版本、安装必要的软件包、配置防火墙等步骤。同时,还强调了使用阿里云服务器时的特殊配置需求,以及建议至少4GB的可用RAM来运行GitLab。 ... [详细]
  • Python语法上的区别及注意事项
    本文介绍了Python2x和Python3x在语法上的区别,包括print语句的变化、除法运算结果的不同、raw_input函数的替代、class写法的变化等。同时还介绍了Python脚本的解释程序的指定方法,以及在不同版本的Python中如何执行脚本。对于想要学习Python的人来说,本文提供了一些注意事项和技巧。 ... [详细]
  • 本文介绍了在Linux下安装Perl的步骤,并提供了一个简单的Perl程序示例。同时,还展示了运行该程序的结果。 ... [详细]
  • Android开发实现的计时器功能示例
    本文分享了Android开发实现的计时器功能示例,包括效果图、布局和按钮的使用。通过使用Chronometer控件,可以实现计时器功能。该示例适用于Android平台,供开发者参考。 ... [详细]
  • 本文介绍了lua语言中闭包的特性及其在模式匹配、日期处理、编译和模块化等方面的应用。lua中的闭包是严格遵循词法定界的第一类值,函数可以作为变量自由传递,也可以作为参数传递给其他函数。这些特性使得lua语言具有极大的灵活性,为程序开发带来了便利。 ... [详细]
  • 在Android开发中,使用Picasso库可以实现对网络图片的等比例缩放。本文介绍了使用Picasso库进行图片缩放的方法,并提供了具体的代码实现。通过获取图片的宽高,计算目标宽度和高度,并创建新图实现等比例缩放。 ... [详细]
  • Nginx使用(server参数配置)
    本文介绍了Nginx的使用,重点讲解了server参数配置,包括端口号、主机名、根目录等内容。同时,还介绍了Nginx的反向代理功能。 ... [详细]
  • 本文详细介绍了Linux中进程控制块PCBtask_struct结构体的结构和作用,包括进程状态、进程号、待处理信号、进程地址空间、调度标志、锁深度、基本时间片、调度策略以及内存管理信息等方面的内容。阅读本文可以更加深入地了解Linux进程管理的原理和机制。 ... [详细]
  • 计算机存储系统的层次结构及其优势
    本文介绍了计算机存储系统的层次结构,包括高速缓存、主存储器和辅助存储器三个层次。通过分层存储数据可以提高程序的执行效率。计算机存储系统的层次结构将各种不同存储容量、存取速度和价格的存储器有机组合成整体,形成可寻址存储空间比主存储器空间大得多的存储整体。由于辅助存储器容量大、价格低,使得整体存储系统的平均价格降低。同时,高速缓存的存取速度可以和CPU的工作速度相匹配,进一步提高程序执行效率。 ... [详细]
  • 自动轮播,反转播放的ViewPagerAdapter的使用方法和效果展示
    本文介绍了如何使用自动轮播、反转播放的ViewPagerAdapter,并展示了其效果。该ViewPagerAdapter支持无限循环、触摸暂停、切换缩放等功能。同时提供了使用GIF.gif的示例和github地址。通过LoopFragmentPagerAdapter类的getActualCount、getActualItem和getActualPagerTitle方法可以实现自定义的循环效果和标题展示。 ... [详细]
  • 本文介绍了Linux Shell中括号和整数扩展的使用方法,包括命令组、命令替换、初始化数组以及算术表达式和逻辑判断的相关内容。括号中的命令将会在新开的子shell中顺序执行,括号中的变量不能被脚本余下的部分使用。命令替换可以用于将命令的标准输出作为另一个命令的输入。括号中的运算符和表达式符合C语言运算规则,可以用在整数扩展中进行算术计算和逻辑判断。 ... [详细]
  • 31.项目部署
    目录1一些概念1.1项目部署1.2WSGI1.3uWSGI1.4Nginx2安装环境与迁移项目2.1项目内容2.2项目配置2.2.1DEBUG2.2.2STAT ... [详细]
author-avatar
无敌lili699_461
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有