美文网首页iOS-地图
在iOS地图上绘制多点间路线

在iOS地图上绘制多点间路线

作者: 阿凡提说AI | 来源:发表于2016-12-02 16:27 被阅读655次

    当我们获取了一组地理位置后,可能会想要在地图上绘制这组地理位置信息所包含的路线。

    MKMapView提供了addOverlay功能(以及addAnnotation),让我们可以在地图上放一层遮罩。如果要放一组遮罩,可以用addOverlays。

    - (void)drawLineWithLocationArray:(NSArray *)locationArray
    {
        NSUInteger pointCount = [locationArray count];
        CLLocationCoordinate2D *coordinateArray = (CLLocationCoordinate2D *)malloc(pointCount * sizeof(CLLocationCoordinate2D));
        
        for (int i = 0; i < pointCount; ++i) {
            CLLocation *location = [locationArray objectAtIndex:i];
            coordinateArray[i] = [location coordinate];
        }
        
        self.routeLine = [MKPolyline polylineWithCoordinates:coordinateArray count:pointCount];
        
    //    [self.mapView setVisibleMapRect:[self.routeLine boundingMapRect]];
        [self.mapView addOverlay:self.routeLine];
        [self.lines addObject:self.routeLine];
        free(coordinateArray);
        coordinateArray = NULL;
    }
    

    MKPolyLine为我们提供了方便绘制多条线段的功能,它实现了MKOverlay协议,但并不能作为遮罩。我们需要实现相应的遮罩代理方法:

    - (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id<MKOverlay>)overlay
    {
        if(overlay == self.routeLine) {
            
                self.routeLineView = [[MKPolylineView alloc] initWithPolyline:self.routeLine];
                self.routeLineView.fillColor = [UIColor redColor];
                self.routeLineView.strokeColor = [UIColor redColor];
                self.routeLineView.lineWidth = 5;
            
               return self.routeLineView;
        }
        return nil;
    }
    

    下面是我的测试代码,用北京的经纬度和杭州的经纬度画线:

    - (void)drawTestLine  
    {  
        CLLocation *location0 = [[CLLocation alloc] initWithLatitude:39.954245 longitude:116.312455];  
        CLLocation *location1 = [[CLLocation alloc] initWithLatitude:30.247871 longitude:120.127683];  
        NSArray *array = [NSArray arrayWithObjects:location0, location1, nil];  
        [self drawLineWithLocationArray:array];  
    }  
    

    相关文章

      网友评论

        本文标题:在iOS地图上绘制多点间路线

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