SVG画出直线加箭头

by Mike Lin

HTML

<link rel="stylesheet" href="https://cache.amap.com/lbs/static/main1119.css">
<script src="https://cache.amap.com/lbs/static/es5.min.js"></script>
<script src="https://webapi.amap.com/maps?v=1.3&amp;key=a5ebc730f80db3b1375a691afad00942"></script>
<script src="https://cache.amap.com/lbs/static/addToolbar.js"></script>
<body>
<div id="container"></div>
</body>

JavaScript

const fromPosition = [116.397428, 39.90923]
const toPositon = [116.457211, 39.99999]

var map = new AMap.Map('container', {
    resizeEnable: true,
    zoom:11,
    center: fromPosition

});
const color = "#00bcd4"
const fromPixel = map.lnglatTocontainer(fromPosition)
const toPixel = map.lnglatTocontainer(toPositon)

const dx = toPixel.getX() - fromPixel.getX()
const dy = toPixel.getY() - fromPixel.getY()
// 计算轨迹的角度
let theta = Math.atan2(dy, dx)
theta *= 180 / Math.PI

const arrowContent = `<svg width="40" height="20" style="transform: rotate(${theta-180}deg); transform-origin: 0% 50%;">
  <g fill="transparent" stroke="${color}" stroke-width="3">
          <path d="M0, 10 L 40 20 L 40 0 Z" />
  </g>
</svg>`

const polyline = new AMap.Polyline({
  path: [fromPosition, toPositon],
  strokeColor: color,
  strokeOpacity: 1,
  strokeStyle: "solid",
  strokeWeight: 3,
  strokeDasharray: [10, 5]
})
polyline.setMap(map)
const arrowMarker = new AMap.Marker({
  position: toPositon,
  content: arrowContent,
  offset: new AMap.Pixel(0, -10),
	map: map
})
arrowMarker.setMap(map)