IOS开发学习笔记(十七)——使用地理位置及地图(中篇)

添加叠加层

现在我们演示如何在地图上叠加你想要的叠加层,我们演示几个效果:圆形、多边形、线条。

基本步骤都差不多(首先以圆形叠加层演示):

添加圆形叠加层

  1. 建立一个新的工程,添加MapKit.framework;
  2. 在界面中放置MapView并设置其属性;
  3. 添加MapView的outlet;
  4. 设置初始化的显示区域:
    #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

  5. 使得ViewController实现MKMapViewDelegate代理;
  6. 添加一个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];
    }

  7. 添加代理方法实现:
    - (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;
    }

  8. 完成,查看效果。

添加多边形叠加层

基本步骤差不多,有细微差别。

  1. 初始化的地方修改为将多边形添加到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];
    }

  2. 代理方法修改:
    - (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;
    }

  3. 完成,查看效果。

从xml中获取数据源

这个步骤比以前多了获取数据这一块:

  1. ViewController需要实现NSXMLParserDelegate代理;
  2. 初始化的时候设置代理并获取数据:
    - (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.");
        }
    }

  3. 编写代理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。
  4. 编写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;
    }

  5. 完成,查看效果。

绘制线段

绘制线段就简单太多,只需要如下步骤:

  1. 初始化的地方初始化线段值:
    - (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];
    }

  2. 代理方法中使用指定选段的模型:
    - (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;
    }
    注意设置线段模型的主要是lineDashPattern和lineWidth。
  3. 完成,查看效果。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值