Qml地图中提供了MapPolyline用于在地图上绘制路线,但是该控件无法显示目标的方位矢量,因此我在MapPolyline的基础上制作了MyMapVectorLine,该控件可自定义矢量标志图片样式,并根据存入数据自动计算标志方位朝向,组件颜色和标志可动态设置,效果如图:
MyMapVectorLine属性:
color:路径和标志颜色
lineWidth:路径线宽度
markWidth:标志的宽
markHeight:设置标志的高
markSource:设置标志的图片源
MyMapVectorLine方法:
appendPoint(coordinate c):往矢量路径中添加经纬度数据,数据添加后组件会根据最新数据方位设置标志朝向
removePoint():从矢量路径中移除最后一个数据,该数据移除后组件会根据最新数据方位设置标志朝向
clear():清空矢量路径中的所有数据
Demo地址(MyMapVectorLine.qml组件已在Demo中加载):
MyMapVectorLinehttps://github.com/zjgo007/QmlDemo/tree/master/MyMapVectorLine
MyMapVectorLine源码:
import QtQuick 2.9
import QtLocation 5.9
import QtQml 2.9
import QtGraphicalEffects 1.0
MapItemGroup{
id:vectorLine
property color color: "green"
property int lineWidth: 2
property int markWidth: 24
property int markHeight: 24
property string markSource: ""
MapPolyline{
id:line
line.width: lineWidth
line.color: color
}
MapQuickItem {
id:mark
width: markWidth
height: markHeight
anchorPoint.x: markWidth/2
anchorPoint.y: markHeight/2
visible: false
sourceItem: Image {
id:image
source: markSource
sourceSize.width: markWidth
sourceSize.height: markHeight
ColorOverlay {
anchors.fill: image
source: image
color: vectorLine.color
}
}
}
function appendPoint(coordinate){
line.addCoordinate(coordinate)
updateMarkRotation()
}
function removePoint(){
var index = line.pathLength()-1
line.removeCoordinate(index)
updateMarkRotation()
}
function clear(){
line.path = []
updateMarkRotation()
}
function updateMarkRotation(){
var size = line.pathLength()
if(size<2){
mark.visible = false
return
}
var cCoordinate = line.coordinateAt(size-1)
var lCoordinate = line.coordinateAt(size-2)
mark.visible = true
mark.coordinate = cCoordinate
var rotation = lCoordinate.azimuthTo(cCoordinate)
mark.rotation = rotation
}
}