使用D3.js创建一个ToolTip
var tooltip = d3.select("body").append("div")
.attr("class","tooltip")
.attr("opacity",0.0);
设置画布并绘制路网图:
这里同时加载完了路网的基础数据
<svg class ="changsha"></svg>
<script>
const svgWidth = 1380;
const svgHeight =900;
const padding = 0;
const svg = d3.select(".changsha")
.attr("height", svgHeight)
.attr("width", svgWidth);
<svg class ="changsha"></svg>
<script>
const svgWidth = 1380;
const svgHeight =900;
const padding = 0;
const svg = d3.select(".changsha")
.attr("height", svgHeight)
.attr("width", svgWidth);
* 创建一个地理投影
* .center 设置投影中心位置
* .scale 设置缩放系数
const x0 = padding;
const y0 = padding;
const x1 = svgWidth - padding * 2;
const y1 = svgHeight - padding * 2;
const projection = d3.geoMercator().fitExtent(
[x0,y0],
[x1,y1],
],changsha
var path = d3.geoPath().projection(projection);
* 渲染地图
const mapPath = svg.selectAll("path");
mapPath.data(changsha.features)
.join('path')
.attr('d', path)
.attr("stroke-width", 2)
.attr("stroke", "#00cc00")
.attr("fill", "#000000")
* 创建一个地理投影
* .center 设置投影中心位置
* .scale 设置缩放系数
const x0 = padding;
const y0 = padding;
const x1 = svgWidth - padding * 2;
const y1 = svgHeight - padding * 2;
const projection = d3.geoMercator().fitExtent(
[x0,y0],
[x1,y1],
],changsha
var path = d3.geoPath().projection(projection);
* 渲染地图
const mapPath = svg.selectAll("path");
mapPath.data(changsha.features)
.join('path')
.attr('d', path)
.attr("stroke-width", 2)
.attr("stroke", "#00cc00")
.attr("fill", "#000000")
绘制结果:
STOMP传送数据分析:
利用stomp-websocket运行服务器向客户端实时发送数据,详细实现请参照:道路实时变色
这里我服务器传送的数据结构是这样的:
也就是一次传送一种颜色(图中:"#00cc00"),后面跟的数组就是随机的升序数组。根据这个数组改变对应次序的path标签的颜色。
可以看到对应次序的path标签stroke的值已经改变了.
鼠标移入移出事件
总算到核心代码了,感觉自己好啰嗦啊哈哈哈
值得一提的是,version 6 以上的D3.JS已经移除了d3.event和与之相关的函数,想要通过D3获取鼠标位置,取而代之的方法是d3.pointer。详细见代码。
另外,我的function(d,i)写法也有问题,最新的版本应该理解为的function(event,d) 也就是说:第一个参数为事件,第二个为对应数据。 详见官方文档
svg.selectAll('path')
.on("mouseover",function (d,i) {
var name = i.properties.name;
var osm_id = i.properties.osm_id;
var p = d3.pointer(d);
var color = d3.select(this).attr("stroke")
tooltip
.html(function(){
var road;
var status;
if(name == null){
road = ["暂无信息"];
else{
road = [""+name];
switch (color){
case '#00cc00': status = "正常";break;
case '#ffff00': status = "车流量大";break;
case '#ff0000': status = "堵塞";break;
default : status = "正常";
return road +"
"+"
"+status
.style("left",(p[0] +35)+"px")
.style("top", (p[1] )+"px")
.style("opacity",1.0);
.on("mouseout",function (d,i) {
tooltip.style("opacity",0.0);