美文网首页百度地图相关
根据地图经纬度,描点划出路线

根据地图经纬度,描点划出路线

作者: Emily_甜心 | 来源:发表于2015-08-25 12:25 被阅读3587次
    给折线定义坐标,然后把折线加到地图上

    <br />
    代码中locations是存放了地图经纬度的一些点。

    官方给出了2个API

    • 方法一:<br />
      + (instancetype)polylineWithPoints:(MKMapPoint *)points <br />count:(NSUInteger)count;
    MKMapPoint *arrayPoint = malloc(sizeof(MKMapPoint) * locations.count); // 这块必须动态分派内存,具体为什么,还不知道。用malloc分配内存在堆内分配内存,用完改变量后,必须手动释放内存。
    for (int i = 0; i < locations.count; i++) {
        CLLocation   *location = [locations objectAtIndex:i];
        MKMapPoint point = MKMapPointForCoordinate(location.coordinate);
        arrayPoint[i] = point;
    }
    MKPolyline *line = [MKPolyline polylineWithPoints:arrayPoint count:locations.count];
    [_mapView addOverlay:line];
    free(arrayPoint);
    
    • 方法二:<br />
      + (instancetype)polylineWithCoordinates:(CLLocationCoordinate2D *)coords count:(NSUInteger)count;
      CLLocationCoordinate2D *coords = malloc(sizeof(CLLocationCoordinate2D) * locations.count);
    for (int i = 0; i < locations.count; i++) {
        NSLog(@"%@",locations[i]);
        CLLocation *location =  locations[i];
        coords[i] = [location coordinate];
    }
    
    MKPolyline *polyline = [MKPolyline polylineWithCoordinates:coords count:locations.count];
    [_mapView addOverlay:polyline];
    free(coords);
    

    *** 遗留问题 ***

    之前尝试 MKMapPoint *arrayPoint[locations.count];
    

    但是当程序执行到arrayPoint[i] = point;时,arrayPoint的值始终是nil,
    始终不得其解,后来看了官网demo,给MKMapPoint实例出的对象分派内存是这样的,malloc(sizeof(MKMapPoint) * locations.count); 改了之后,程序OK。

    可能OC比较特殊吧,要求指针一定得是堆上的,栈里面的变量不行。Swift语言的话直接用数组就可以了。知道原因的大神,不吝赐教。
    

    *** 注意事项 ***

    malloc动态分配内存,记得用完该变量记得free

    调用MKMapView代理方法进行覆盖物加载
    - (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay {
    
        if ([overlay isKindOfClass:[MKPolyline class]]) {
            MKPolylineRenderer *overlayRenderer = [[MKPolylineRenderer alloc] initWithPolyline:overlay];
            overlayRenderer.strokeColor = [UIColor blueColor];
            overlayRenderer.fillColor = [UIColor blueColor];
            overlayRenderer.lineWidth = 3;
        
            return overlayRenderer;
    
     }
    
        return nil;
    }
    

    iOS7 之前加载覆盖物划线用下面的方法<br />
    - (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay ;<br />
    iOS7 之后该方法弃用,改用<br />
    - (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay

    相关文章

      网友评论

      • blocky:在吗 按这么写总是不成功
      • 奔跑的蔬菜:使用系统地图在拖动,缩放的时候内存激增. 有的时候还崩溃了. 请问楼主是怎么解决的
      • 张小小白:亲,有个demo吗?最近在搞这个,总是崩溃
      • xxttw:我最近也做了你这个需求.但是对malloc(sizeof(CLLocationCoordinate2D) * locations.count);
        for (int i = 0; i < locations.count; i++) {这段 malloc 代码不是很懂.有知道的大神吗

      本文标题:根据地图经纬度,描点划出路线

      本文链接:https://www.haomeiwen.com/subject/fclqcttx.html