添加叠加层
现在我们演示如何在地图上叠加你想要的叠加层,我们演示几个效果:圆形、多边形、线条。
基本步骤都差不多(首先以圆形叠加层演示):
添加圆形叠加层
- 建立一个新的工程,添加MapKit.framework;
- 在界面中放置MapView并设置其属性;
- 添加MapView的outlet;
- 设置初始化的显示区域:
#import "ViewController.h" // ShangHai #define SH_LATITUDE 31.14 #define SH_LONGITUDE 121.29 // Span #define SPAN_VALUE 2.0f @interface ViewController () @end @implementation ViewController @synthesize mapView; - (void)viewDidLoad { [super viewDidLoad]; CLLocationCoordinate2D center; center.latitude = SH_LATITUDE; center.longitude = SH_LONGITUDE; MKCoordinateSpan span; span.latitudeDelta = SPAN_VALUE; span.longitudeDelta = SPAN_VALUE; MKCoordinateRegion region; region.center = center; region.span = span; [self.mapView setRegion:region animated:YES]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
- 使得ViewController实现MKMapViewDelegate代理;
- 添加一个Overlay,使得viewDidLoad变为:
- (void)viewDidLoad { [super viewDidLoad]; // set the delegate to it self [self.mapView setDelegate:self]; // set init region of the mapview CLLocationCoordinate2D center; center.latitude = SH_LATITUDE; center.longitude = SH_LONGITUDE; MKCoordinateSpan span; span.latitudeDelta = SPAN_VALUE; span.longitudeDelta = SPAN_VALUE; MKCoordinateRegion region; region.center = center; region.span = span; [self.mapView setRegion:region animated:YES]; // center is the circle's center point, radius 2000 means 2 kilometers; MKCircle *circle = [MKCircle circleWithCenterCoordinate:center radius:2000]; [self.mapView addOverlay:circle]; }
- 添加代理方法实现:
- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id < MKOverlay >)overlay { MKCircleView *view = [[MKCircleView alloc] initWithOverlay: overlay]; view.fillColor = [[UIColor purpleColor] colorWithAlphaComponent: 0.5f]; view.strokeColor = [[UIColor yellowColor] colorWithAlphaComponent: 0.8f]; view.lineWidth = 1; return view; }
- 完成,查看效果。
添加多边形叠加层
基本步骤差不多,有细微差别。
- 初始化的地方修改为将多边形添加到map view:
- (void)viewDidLoad { [super viewDidLoad]; // set the delegate to it self [self.mapView setDelegate:self]; // set init region of the mapview CLLocationCoordinate2D center; center.latitude = SH_LATITUDE; center.longitude = SH_LONGITUDE; MKCoordinateSpan span; span.latitudeDelta = SPAN_VALUE; span.longitudeDelta = SPAN_VALUE; MKCoordinateRegion region; region.center = center; region.span = span; [self.mapView setRegion:region animated:YES]; // center is the circle's center point, radius 2000 means 2 kilometers; MKCircle *circle = [MKCircle circleWithCenterCoordinate:center radius:2000]; [self.mapView addOverlay:circle]; // create polygon CLLocationCoordinate2D coordinates[4] = {{31.232, 121.264}, {31.288, 121.326}, {31.180, 121.275}, {31.25, 121.35}}; MKPolygon *polygon = [MKPolygon polygonWithCoordinates: coordinates count: 4]; // add polygon to map [self.mapView addOverlay: polygon]; }
- 代理方法修改:
- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id < MKOverlay >)overlay { if ([overlay isKindOfClass: [MKCircle class]]) { MKCircleView *view = [[MKCircleView alloc] initWithOverlay: overlay]; view.fillColor = [[UIColor greenColor] colorWithAlphaComponent: 0.5f]; view.strokeColor = [[UIColor redColor] colorWithAlphaComponent: 0.8f]; view.lineWidth = 1; return view; } if ([overlay isKindOfClass: [MKPolygon class]]) { MKPolygonView *view = [[MKPolygonView alloc] initWithOverlay: overlay]; view.fillColor = [[UIColor purpleColor] colorWithAlphaComponent: 0.5f]; view.strokeColor = [[UIColor yellowColor] colorWithAlphaComponent: 0.8f]; view.lineWidth = 1; return view; } return nil; }
- 完成,查看效果。
从xml中获取数据源
这个步骤比以前多了获取数据这一块:
- ViewController需要实现NSXMLParserDelegate代理;
- 初始化的时候设置代理并获取数据:
- (void)viewDidLoad { [super viewDidLoad]; // set the mapview delegate to it self [self.mapView setDelegate:self]; // load XML and initialize parsing NSString *path = [[NSBundle mainBundle] resourcePath]; NSString *xml = [path stringByAppendingPathComponent:@"data.xml"]; NSURL *url = [NSURL fileURLWithPath:xml isDirectory:NO]; NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:url]; parser.delegate = self; BOOL success = [parser parse]; if (!success) { NSLog(@"parse xml file failed."); } }
- 编写代理NSXMLParserDelegate的实现方法:
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict { if ([elementName isEqualToString:@"ca"]) { // if element name is 'ca', start create array temp = [[NSMutableArray alloc]init]; } else if ([elementName isEqualToString:@"point"]) { // if element name is 'point', add a polygon point & init the point value: 'lat' & 'lng' NSDictionary *point = [[NSDictionary alloc] initWithObjectsAndKeys:[attributeDict objectForKey:@"lat"], @"latitude", [attributeDict objectForKey:@"lng"], @"longitude", nil]; [temp addObject:point]; } } - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { if ([elementName isEqualToString:@"ca"]) { // now is the end of the array data, so we must create a coor array to paint the polygon point CLLocationCoordinate2D *coordinates = malloc(sizeof(CLLocationCoordinate2D) * [temp count]); for (int i = 0; i < [temp count]; i++) { NSDictionary *dict = [temp objectAtIndex:i]; double lat = [[dict valueForKey:@"latitude"] doubleValue]; double lon = [[dict valueForKey:@"longitude"] doubleValue]; CLLocationCoordinate2D point; point.latitude = lat; point.longitude = lon; coordinates[i] = point; } // create polygon from coordinates MKPolygon *polygon = [MKPolygon polygonWithCoordinates:coordinates count:[temp count]]; [self.mapView addOverlay:polygon]; // scale map to display polygon [self.mapView setVisibleMapRect:polygon.boundingMapRect]; free(coordinates); } }
注意需要定义一个tmp的NSMutableArray。 - 编写viewForOverlay实现方法:
- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id<MKOverlay>)overlay { MKPolygonView *polygonView = [[MKPolygonView alloc] initWithPolygon:overlay]; polygonView.fillColor = [[UIColor cyanColor] colorWithAlphaComponent:0.5]; polygonView.strokeColor = [[UIColor blueColor] colorWithAlphaComponent:0.6]; polygonView.lineWidth = 1; return polygonView; }
- 完成,查看效果。
绘制线段
绘制线段就简单太多,只需要如下步骤:
- 初始化的地方初始化线段值:
- (void)viewDidLoad { [super viewDidLoad]; // set the mapview delegate to it self [self.mapView setDelegate:self]; CLLocationCoordinate2D coordinates[4] = {{31.202, 121.23}, {31.288, 121.326}, {31.180, 121.275}, {31.25, 121.35}}; MKPolyline *line = [MKPolyline polylineWithCoordinates:coordinates count:4]; [self.mapView addOverlay: line]; // scale the map so we can see the whole area [self.mapView setVisibleMapRect: line.boundingMapRect]; }
- 代理方法中使用指定选段的模型:
注意设置线段模型的主要是lineDashPattern和lineWidth。- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id<MKOverlay>)overlay { MKPolylineView *view = [[MKPolylineView alloc] initWithOverlay:overlay]; view.strokeColor = [[UIColor redColor] colorWithAlphaComponent:0.5]; // starting with the first line segment length, followed by the first gap length, followed by the second line segment length, and so on. NSArray *pattern = [NSArray arrayWithObjects:[NSNumber numberWithInt:20], [NSNumber numberWithInt: 10], nil]; view.lineDashPattern = pattern; view.lineWidth = 3; return view; }
- 完成,查看效果。