歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> iPhone開發之繪制地圖線路

iPhone開發之繪制地圖線路

日期:2017/3/1 10:18:40   编辑:Linux編程
地圖應用經常會涉及到線路的繪制問題,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. #import <UIKit/UIKit.h>
  9. #import <MapKit/MapKit.h>
  10. #import "CloMKAnnotation.h"
  11. @interface CloViewController : UIViewController<CLLocationManagerDelegate, MKMapViewDelegate, UIActionSheetDelegate>{
  12. MKMapView *cloMapView;
  13. MKPolyline *routeLine;
  14. }
  15. @property (nonatomic, strong) NSMutableArray *locations;
  16. @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. #import "CloViewController.h"
  9. @interface CloViewController ()
  10. @end
  11. @implementation CloViewController
  12. @synthesize locations;
  13. - (void)viewDidLoad
  14. {
  15. [super viewDidLoad];
  16. // Do any additional setup after loading the view, typically from a nib.
  17. cloMapView = [[MKMapView alloc] initWithFrame:[self.view bounds]];
  18. [cloMapView setMapType:MKMapTypeHybrid]; //設置地圖類型 地圖/衛星/兩者結合
  19. [cloMapView setShowSUSErLocation:YES]; //顯示當前位置
  20. [cloMapView setDelegate:self];
  21. CLLocationManager *locationManager = [[CLLocationManager alloc] init];
  22. //設置CLLocationManager實例委托和精度
  23. [locationManager setDelegate:self];
  24. [locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
  25. //設置距離篩選器,表示至少移動100米才通知委托更新
  26. [locationManager setDistanceFilter:100.f];
  27. //啟動更新請求
  28. // [locationManager startUpdatingLocation];
  29. locations = [[NSMutableArray alloc] init];
  30. float latitude = 39.8127; //維度
  31. float longitude = 116.2967; //經度
  32. for (int i = 0; i < 10; i++) {
  33. [locations addObject:[NSString stringWithFormat:@"%f,%f", latitude + 0.01*i, longitude + 0.01*i]];
  34. // NSLog(@"locations:%i",locations.count);
  35. }
  36. //地圖初始
  37. CLLocationCoordinate2D coords;
  38. coords.latitude = 39.9127;
  39. coords.longitude = 116.3967;
  40. float zoomlevel = 0.22;
  41. MKCoordinateRegion region = MKCoordinateRegionMake(coords, MKCoordinateSpanMake(zoomlevel, zoomlevel));
  42. [cloMapView setRegion:[cloMapView regionThatFits:region] animated:YES];
  43. [cloMapView addOverlay:[self makePolylineWithLocations:locations]];
  44. [self.view addSubview:cloMapView];
  45. }
  46. - (void)viewDidUnload
  47. {
  48. [super viewDidUnload];
  49. // Release any retained subviews of the main view.
  50. cloMapView = nil;
  51. }
  52. - (void)dealloc{
  53. [cloMapView release];
  54. [super dealloc];
  55. }
  56. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
  57. {
  58. return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
  59. }
  60. //顯示菜單選項
  61. - (void)showActionSheet :(id)sender{
  62. UIActionSheet * actionSheet = [[UIActionSheet alloc] initWithTitle:nil
  63. delegate:self
  64. cancelButtonTitle:@"取消"
  65. destructiveButtonTitle:@"添加足跡"
  66. otherButtonTitles:@"分享",@"詳細",@"刪除", nil];
  67. [actionSheet setDelegate:self];
  68. [actionSheet showInView:self.view];
  69. [actionSheet release];
  70. }
  71. //根據坐標點生成線路
  72. - (MKPolyline *)makePolylineWithLocations:(NSMutableArray *)newLocations{
  73. MKMapPoint *pointArray = malloc(sizeof(CLLocationCoordinate2D)* newLocations.count);
  74. for(int i = 0; i < newLocations.count; i++)
  75. {
  76. // break the string down even further to latitude and longitude fields.
  77. NSString* currentPointString = [newLocations objectAtIndex:i];
  78. NSArray* latLonArr = [currentPointString componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@","]];
  79. CLLocationDegrees latitude = [[latLonArr objectAtIndex:0] doubleValue];
  80. // NSLog(@"latitude-> %f", latitude);
  81. CLLocationDegrees longitude = [[latLonArr objectAtIndex:1] doubleValue];
  82. CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(latitude, longitude);
  83. // NSLog(@"point-> %f", point.x);
  84. if (i == 0 || i == locations.count - 1) {//這裡只添加起點和終點作為測試
  85. CloMKAnnotation *ann = [[CloMKAnnotation alloc] init];
  86. [ann setCoordinate:coordinate];
  87. [ann setTitle:[NSString stringWithFormat:@"緯度:%f", latitude]];
  88. [ann setSubtitle:[NSString stringWithFormat:@"經度:%f", longitude]];
  89. [cloMapView addAnnotation:ann];
  90. }
  91. pointArray[i] = MKMapPointForCoordinate(coordinate);
  92. }
  93. routeLine = [MKPolyline polylineWithPoints:pointArray count:newLocations.count];
  94. free(pointArray);
  95. return routeLine;
  96. }
  97. #pragma mark-
  98. #pragma CLLocationManager delegate method
  99. //位置變化後會調用
  100. - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
  101. //可在此處更新用戶位置信息
  102. // cloMapView.userLocation
  103. NSLog(@"oldLocation:%@", [oldLocation description]);
  104. NSLog(@"newLocation:%@", [newLocation description]);
  105. NSLog(@"distance:%@", [newLocation distanceFromLocation:oldLocation]);
  106. //位置變化添加新位置點
  107. [locations addObject:[NSString stringWithFormat:@"%f,%f", newLocation.coordinate.latitude, newLocation.coordinate.longitude]];
  108. //刪除進線路,更新新軌跡
  109. [cloMapView removeOverlay:routeLine];
  110. [cloMapView addOverlay:[self makePolylineWithLocations:locations]];
  111. }
  112. #pragma MKMapView delegate method
  113. //添加坐標點大頭針
  114. - (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{
  115. if (![annotation isKindOfClass:[CloMKAnnotation class]]) {
  116. return nil;
  117. }
  118. static NSString *identifier = @"Annotation";
  119. MKPinAnnotationView *pinAnnotationView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:identifier];
  120. if (pinAnnotationView == nil) {
  121. pinAnnotationView = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifier] autorelease];
  122. }
  123. pinAnnotationView.animatesDrop = YES;
  124. pinAnnotationView.canShowCallout = YES;
  125. pinAnnotationView.draggable = YES;
  126. UIButton *detailBtn = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
  127. [detailBtn addTarget:self action:@selector(showActionSheet:) forControlEvents:UIControlEventTouchUpInside];
  128. pinAnnotationView.rightCalloutAccessoryView = detailBtn;
  129. return pinAnnotationView;
  130. }
  131. - (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view didChangeDragState:(MKAnnotationViewDragState)newState fromOldState:(MKAnnotationViewDragState)oldState{
  132. }
  133. //畫線
  134. - (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id<MKOverlay>)overlay{
  135. NSLog(@"return overLayView...");
  136. if ([overlay isKindOfClass:[MKPolyline class]]) {
  137. MKPolylineView *routeLineView = [[[MKPolylineView alloc] initWithPolyline:routeLine] autorelease];
  138. routeLineView.strokeColor = [UIColor blueColor];
  139. routeLineView.lineWidth = 3;
  140. return routeLineView;
  141. }
  142. return nil;
  143. }
  144. @end
這裡主要是為了測試,初始時 locations坐標點自定義的,實際中是根據用戶的位置動態生成的一系列坐標點。具體可在
  1. - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
函數中實現,如上代碼。

另外用戶的實時位置可用

  1. cloMapView.userLocation = newLocation進行設置,然後顯示在地圖上。
效果圖如下:

Copyright © Linux教程網 All Rights Reserved