效果:
框架:vue-baidu-map
主要代码:
<baidu-map
ref="map"
class="bm-view"
ak="IoC3dZUFGLc7AP7uPiQxBqA7QtcvQ7dU"
:center="center"
:zoom="zoom"
:scroll-wheel-zoom="true"
@ready="handler"
@zoomend="onZoomend"
:class="baiduMapShow && 'readyMap'"
>
<bm-polyline
v-for="(item, index) in polylinePath"
:key="index"
:path="item"
stroke-color="url(#MyGradient)"
:stroke-opacity="1"
:stroke-weight="8"
strokeStyle="solid"
:editing="false"
></bm-polyline>
<my-overlay
v-for="(item, index) in allPoint"
:key="index"
:position="item.center"
:status="item.status"
>
</my-overlay>
</baidu-map>
使用了画线的标签<bm-polyline></bm-polyline>
,但是想要画出圆滑的曲线,得尽量拿到更多的坐标点,于是我想着,可不可以用路径的起始坐标获取到整条路径的坐标呢?查询了资料以及文档后发现还是有办法可以获取到的;剩下的就是渐变了,参考了网上的几种方法,都没达到效果,CanvasLayer本来以为可以实现,没想到…因为使用的是canvas画折线的方法画的,坐标点一多,渐变就成了如图
oh~失败。canvas不行,那就试试svg,打开控制台一看,百度地图的线段,就是用svg画的,于是想起了最原始的办法,简单粗暴操作dom…于是就这么画出了一条渐变轨迹。
handler({ BMap, map }) {
this.map = map; //百度地图实例化对象
this.BMap = BMap;
map.setMapStyleV2({
styleId: "02b81ab7cd95f6aece86c3500bf9b3cf",
});
this.center.lng = 113.270218;
this.center.lat = 23.134245;
this.zoom = 15;
this.baiduMapShow = true;
this.linePoint.map((item) => {
this.allPoint.push(...item);
this.road.push([item[0], item[item.length - 1]]);
});
setTimeout(() => {
// 插入渐变
let mapE = document.getElementsByClassName("bm-view")[0];
let svgE = mapE.getElementsByTagName("svg");
let def = `<defs>
<linearGradient id="MyGradient">
<stop offset="0%" stop-color="rgba(98,242,255,0.28)" />
<stop offset="50%" stop-color="rgba(75,234,255,1)" />
<stop offset="100%" stop-color="rgba(51,225,255,0.02)" />
</linearGradient>
</defs>`;
if (svgE.length) {
for(let i in svgE) {
svgE[i].insertAdjacentHTML("afterBegin", def);
}
}
}, 1000);
if (this.road.length) {
this.road.map((item) => {
let startP = item[0].center;
let endP = item[1].center;
this.getPoints(startP, endP);
});
}
// this.drawPath();
},
// 根据道路起始点获取道路所有坐标点
getPoints(start, end) {
let that = this;
const myP1 = new this.BMap.Point(start.lng, start.lat); //起点
const myP2 = new this.BMap.Point(end.lng, end.lat); //终点
let driving = new this.BMap.DrivingRoute(
this.map,
{
onSearchComplete: function (results) {
if (driving.getStatus() == BMAP_STATUS_SUCCESS) {
let pts = driving.getResults().getPlan(0).getRoute(0).getPath(); //通过驾车实例,获得一系列点的数组
that.polylinePath.push(pts);
}
},
},
{ renderOptions: { map: this.map, autoViewport: true } }
); //驾车实例
driving.search(myP1, myP2);
},
第一次接触百度地图,很多api还不熟悉,要是各位大神有更好更简单的办法,还请赐教~
(目前暂时就这么交差先吧==)