根据经纬度坐标绘制轨迹图形
一段时间没更新了,主人最近有点懒~
- 前段时间有个需求,在uniapp App端实现轨迹绘制,于是先用html实现看看效果~
效果图
html
<canvas
id="canvasId"
width="300"
height="300"
style="border: 1px solid red"
>
</canvas>
js
<script>
// mock data
let locationList = [
{
"lng": 113.98049,
"lat": 22.54301
},
{
"lng": 113.972839,
"lat": 22.533976
},
{
"lng": 113.98925,
"lat": 22.524669
},
{
"lng": 113.990034,
"lat": 22.537097
},
{
"lng": 114.00916,
"lat": 22.534477
}
];
// canvas元素宽高
let canvasHeight = 300,
canvasWidth = 300;
// 遍历数据,把所有经、纬度分别添加数组中【目的:是得到各个方向轴的最大最小值】
let amuXArr = [], // [22.54301, 22.51134, 22.50951, 22.51031, 22.54611]
amuYArr = []; // [113.98049, 114.06374, 114.06259, 114.06178, 113.96047]
for (let i = 0; i < locationList.length; i++) {
amuXArr.push(locationList[i].lat);
amuYArr.push(locationList[i].lng);
}
// y轴需要进行取负操作 [-113.98049, -114.06374, -114.06259, -114.06178, -113.96047]
amuYArr = amuYArr.map((item) => {
return item * -1;
});
// 拿到方向轴的最大最小值
let xMax = Math.max(...amuXArr);
let xMin = Math.min(...amuXArr);
let yMax = Math.max(...amuYArr);
let yMin = Math.min(...amuYArr);
console.log("拿到方向轴的最大最小值:", xMax, xMin, yMax, yMin);
// 根据canvas宽高计算缩放级别
let xScale = canvasWidth / (xMax - xMin);
let yScale = canvasHeight / (yMax - yMin);
let scale = xScale < yScale ? xScale : yScale;
// 计算偏移量
let xoffset = (canvasWidth - (xMax - xMin) * scale) / 2;
let yoffset = (canvasHeight - (yMax - yMin) * scale) / 2;
let canvas = document.getElementById("canvasId");
let ctx = canvas.getContext("2d");
// 平移原点并旋转画布
ctx.translate(0, canvasHeight);
ctx.rotate(-Math.PI / 2);
ctx.beginPath();
// 根据偏移量移动点位并画图
ctx.moveTo(
(amuXArr[0] - xMin) * scale + xoffset,
(yMax - amuYArr[0]) * scale + yoffset
);
for (let i = 1; i < amuXArr.length; i++) {
ctx.lineTo(
(amuXArr[i] - xMin) * scale + xoffset,
(yMax - amuYArr[i]) * scale + yoffset
);
}
ctx.strokeStyle = '#1FE298';
ctx.closePath();
ctx.stroke();
</script>
参考文章: