<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
<title>自定义图层-SVG</title>
<style>
html,
body,
#container {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div id="container"></div>
<script src="//webapi.amap.com/maps?v=1.4.15&key=您申请的key值"></script>
<script>
var starCenter = [116.306206, 39.975468]
var map = new AMap.Map('container', {
center: starCenter,
zoom: 3,
});
map.plugin(['AMap.CustomLayer'], function () {
var size = map.getSize();
var canvas = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
canvas.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
canvas.setAttribute('width', size.width);
canvas.setAttribute('height', size.height);
path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
path.onclick = function () {
console.log('svg path clicked')
}
var styleText = [];
styleText.push('stroke:red');
styleText.push('fill:green');
styleText.push('fill-opacity:0.3');
path.style.cssText = styleText.join(';');
canvas.appendChild(path)
var customLayer = new AMap.CustomLayer(canvas, {
// zooms: [3, 8],
// alwaysRender:true,
zIndex: 300
});
customLayer.render = onRender;
map.add(customLayer)
});
function buildPath() {
var path = [];
var center = map.lngLatToContainer(starCenter)
for (k = 0; k < 6; k += 1) {
var ag = Math.PI * 60 / 180 * k
var x = center.x + Math.cos(ag) * 50
var y = center.y + Math.sin(ag) * 50
path.push((k == 0 ? 'M' : 'L') + x + ' ' + y);
}
return path.join(' ') + ' Z';
}
function onRender() { //更新路径
var newPath = buildPath();
path.setAttribute('d', newPath);
}
</script>
</body>
</html>