Leaflet+D3: 路径
目录
开发环境
npm install leaflet d3 --save
- leaflet v1.x
- d3 v4.x
根据d3创建svg,并添加到map地图的overlayPane下
var svg = d3.select(mymap.getPanes().overlayPane).append('svg')
.attr('class', 'svgTransform')
.attr("id", "d3_svg");
根据点位坐标 生成线
//线生成器
var lineFunction = d3.line()
.x(function (d) {
return d.x;
})
.y(function (d) {
return d.y;
})
.curve(d3.curveBasis);//线的类型
创建路径
g.append("path")
.attr("d", lineFunction(points))
.attr("stroke", colorArr[0]) //颜色
.attr("fill", "none")
.attr("stroke-width", "2");
将经纬度点转为像素点
points.push(mymap.latLngToLayerPoint([pItme.y, pItme.x]))
注册map zoom 事件
mymap.on('zoom', resetView);
示例代码
<!DOCTYPE html>
<html>
<head>
<title>d3 path</title>
</head>
<link rel="stylesheet" type="text/css" href="node_modules/leaflet/dist/leaflet.css">
<script type="text/javascript" src="node_modules/leaflet/dist/leaflet.js"></script>
<script type="text/javascript" src="node_modules/d3/build/d3.js"></script>
<style>
html,
body {
margin: 0;
padding: 0;
}
#map {
width: 100%;
height: calc(100vh)
}
</style>
<body>
<div id="map"></div>
<script type="text/javascript">
var mymap = L.map('map').setView([35.998, 121.98670782], 4);
L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 18,
noWrap: true
}).addTo(mymap);
var svg = d3.select(mymap.getPanes().overlayPane).append('svg')
.attr('class', 'svgTransform')
.attr("id", "d3_svg");
var colorArr = ["red", "blue", "green", "orange"]
var data = [
[{
x: 110.85099,
y: 39.25962166
}, {
x: 134.537944,
y: 34.63874
}],
[{
x: 120.98670782,
y: 34.99922008
}, {
x: 121.98670782,
y: 35.998
}, {
x: 123.678,
y: 34.744
}, {
x: 124.101,
y: 33.739
}],
[{
x: 123.98670782,
y: 33.99922008
}, {
x: 112.98670782,
y: 34.998
}, {
x: 123.678,
y: 36.744
}, {
x: 134.25,
y: 33.759
}]
];
mymap.on("zoom", resetView)
function resetView() {
d3.selectAll("#pointMove").remove()
addPath()
}
function addPath() {
for (let i = 0; i < data.length; i++) {
var points = []
g = d3.select("#d3_svg")
.append("g")
.attr("id", "pointMove");
var item = data[i];
// to pixelPoint
for (let index = 0; index < item.length; index++) {
var pItme = item[index];
points.push(mymap.latLngToLayerPoint([pItme.y, pItme.x]))
}
//线生成器
var lineFunction = d3.line()
.x(function (d) {
return d.x;
})
.y(function (d) {
return d.y;
})
.curve(d3.curveBasis);
g.append("path")
.attr("d", lineFunction(points))
.attr("stroke", colorArr[0]) //颜色
.attr("fill", "none")
.attr("stroke-width", "2");
g.append("circle")
.attr("r", 1 * (mymap.getZoom() == 0 ? 1 : mymap.getZoom()))
.attr("fill", colorArr[2])
.append('animateMotion')
.attr('path', lineFunction(points))
.attr('rotate', "auto")
.attr('dur', "10s")
.attr('repeatCount', "indefinite");
}
}
function initial() {
svg.attr("width", 1500)
.attr("height", 800);
addPath();
}
initial()
</script>
</body>
</html>
更多内容,欢迎关注公众号
转载自:https://blog.csdn.net/weixin_34113237/article/details/88149670