根据后台返回的经纬度数组,展示一条路线轨迹;
代码如下:
importUIKit
class ColoredLinesViewController: UIViewController, MAMapViewDelegate {
var mapView: MAMapView!
//路线(轨迹)数组。可同时显示多条轨迹
var lines: Array<MAOverlay>!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.gray
//加载地图显示,路线轨迹创建
initMapView()
initLines()
}
func initMapView() {
mapView = MAMapView(frame:self.view.bounds)
mapView.delegate =self
self.view.addSubview(mapView)
}
funcinitLines() {
//轨迹数组初始化,不写会崩溃哦
lines =Array()
//轨迹路线模拟(经纬度数组)
/* Colored Polyline. */
varcoloredPolylineCoords:[CLLocationCoordinate2D] = [CLLocationCoordinate2DMake(39.938698,116.275177),
CLLocationCoordinate2DMake(39.966069,116.289253),
CLLocationCoordinate2DMake(39.944226,116.306076),
CLLocationCoordinate2DMake(39.966069,116.322899),
CLLocationCoordinate2DMake(39.938698,116.336975)];
//这么使用的是 MAMultiPolyline ;还有 MAPolyline,两种线条对象的区别可以自行去查看;
letcoloredPolyline = MAMultiPolyline.init(coordinates: &coloredPolylineCoords, count:UInt(coloredPolylineCoords.count), drawStyleIndexes: [1,3])
lines.append(coloredPolyline!)
/* Gradient Polyline. */
vargradientPolylineCoords:[CLLocationCoordinate2D] = [CLLocationCoordinate2DMake(39.938698,116.351051),
CLLocationCoordinate2DMake(39.966069,116.366844),
CLLocationCoordinate2DMake(39.938698,116.381264),
CLLocationCoordinate2DMake(39.938698,116.395683),
CLLocationCoordinate2DMake(39.950067,116.395683),
CLLocationCoordinate2DMake(39.950437,116.423449),
CLLocationCoordinate2DMake(39.966069,116.423449),
CLLocationCoordinate2DMake(39.966069,116.395683)];
letgradientPolyline = MAMultiPolyline.init(coordinates: &gradientPolylineCoords, count:UInt(gradientPolylineCoords.count), drawStyleIndexes: [0,2,3,7])
lines.append(gradientPolyline!)
//讲轨迹路线添加进地图显示
mapView.addOverlays(lines)
//调用划线后,调用下面方法,设置地图可视矩形的范围(即地图会定位在你想展示那条轨迹的位置,否则地图会默认定位在北京区域)
self.mapView.setVisibleMapRect(coloredPolyline!.boundingMapRect, edgePadding:UIEdgeInsets(top:40, left:40, bottom:40, right:40), animated:true)
}
//MARK: - MAMapViewDelegate. -路线样式设置(宽度,颜色)
funcmapView(_mapView:MAMapView!, rendererFor overlay:MAOverlay!) ->MAOverlayRenderer! {
if(overlay.isKind(of: MAMultiPolyline.self))
{
letrenderer = MAMultiColoredPolylineRenderer.init(multiPolyline: overlayas!MAMultiPolyline!)
renderer?.lineWidth =10.0
letindex = lines.index(where: {$0 === overlay})
if(index ==0) {
renderer?.strokeColors = [UIColor.blue,UIColor.white,UIColor.black,UIColor.green];
renderer?.isGradient =true
}else{
renderer?.strokeColors = [UIColor.red,UIColor.yellow,UIColor.green]
renderer?.isGradient =false
}
returnrenderer;
}
returnnil;
}
}
网友评论