高德地图开发iOS 轻量版地图SDK开发指南与地图交互—绘制折线

高德地图开发iOS 轻量版地图SDK开发指南与地图交互—绘制折线

绘制折线 最后更新时间: 2021年03月10日

折线类为 MAPolyline,由一组经纬度坐标组成,并以有序序列形式建立一系列的线段。iOS SDK支持在3D矢量地图上绘制带箭头或有纹理等样式的折线,同时可设置折线端点和连接点的类型,以满足各种绘制线的场景。  

绘制折线

(1) 修改ViewController.m文件,在viewDidLoad方法中构造折线数据对象(一组经纬度坐标点)。 

Objective-C
Swift

//构造折线数据对象
CLLocationCoordinate2D commonPolylineCoords[4];
commonPolylineCoords[0].latitude = 39.832136;
commonPolylineCoords[0].longitude = 116.34095;
    
commonPolylineCoords[1].latitude = 39.832136;
commonPolylineCoords[1].longitude = 116.42095;
    
commonPolylineCoords[2].latitude = 39.902136;
commonPolylineCoords[2].longitude = 116.42095;
    
commonPolylineCoords[3].latitude = 39.902136;
commonPolylineCoords[3].longitude = 116.44095;
    
//构造折线对象
MAPolyline *commonPolyline = [MAPolyline polylineWithCoordinates:commonPolylineCoords count:4];

//在地图上添加折线对象
[_mapView addOverlay: commonPolyline];
var lineCoordinates: [CLLocationCoordinate2D] = [
	CLLocationCoordinate2D(latitude: 39.855539, longitude: 116.119037),
	CLLocationCoordinate2D(latitude: 39.88539, longitude: 116.250285),
	CLLocationCoordinate2D(latitude: 39.805479, longitude: 116.180859),
	CLLocationCoordinate2D(latitude: 39.788467, longitude: 116.226786),
	CLLocationCoordinate2D(latitude: 40.001442, longitude: 116.353915),
	CLLocationCoordinate2D(latitude: 39.989105, longitude: 116.360200)]
        
let polyline: MAPolyline = MAPolyline(coordinates: &lineCoordinates, count: UInt(lineCoordinates.count))
        
map.add(polyline)

(2) 在 ViewController.m 文件中,实现 <MAMapDelegate> 协议中的 map:rendererForOverlay: 回调函数,设置折线的样式。示例代码如下: 

Objective-C
Swift

- (MAOverlayRenderer *)map:(MAMap *)map rendererForOverlay:(id <MAOverlay>)overlay
{
    if ([overlay isKindOfClass:[MAPolyline class]])
    {
        MAPolylineRenderer *polylineRenderer = [[MAPolylineRenderer alloc] initWithPolyline:overlay];
        
        polylineRenderer.lineWidth    = 8.f;
        polylineRenderer.strokeColor  = [UIColor colorWithRed:0 green:1 blue:0 alpha:0.6];
        polylineRenderer.lineJoinType = kMALineJoinRound;
        polylineRenderer.lineCapType  = kMALineCapRound;
        
        return polylineRenderer;
    }
    return nil;
}
func map(_ map: MAMap!, rendererFor overlay: MAOverlay!) -> MAOverlayRenderer! {
	if (overlay.isKind(of: MAPolylineRenderer.self)) {
		let renderer = MAPolylineRenderer.init(multiPolyline: overlay as! MAPolylineRenderer?)
		renderer?.lineWidth = 8.0
		renderer?.strokeColor = UIColor.init(red: 0, green: 1, blue: 0, alpha: 0.6)
        
		return renderer;
	}
	return nil;
}

运行程序,效果如下所示: