【发布时间】:2020-06-09 09:58:57
【问题描述】:
我一直在玩 d3.js,我一直在尝试创建一个 d3 地图,其中单击州地图上的不同区/县会显示地图旁边的区/县的详细信息。
我最初使用mouseover 和mouseout 来显示相同的内容,但它不适合移动设备。所以现在我正在尝试对onclick 做同样的事情,但它的工作方式不同。
该地区应在点击时改变颜色(它与mouseover 一起使用)。然而,它只有在区域内多次重复随机点击后才会改变颜色。
这就是我所做的。
var width = 345,
height = 450;
var projection = d3.geoMercator()
.center([88.36, 27.58])
.translate([width / 2, height / 2])
.scale(6000);
var path = d3.geoPath()
.projection(projection);
var svg = d3.select('#Sk_Map').append('svg')
.attr('width', width)
.attr('height', height);
var g = svg.append('g');
d3.json('https://raw.githubusercontent.com/shklnrj/IndiaStateTopojsonFiles/master/Sikkim.topojson')
.then(state => {
g.append('path')
.datum(topojson.merge(state, state.objects.Sikkim.geometries))
.attr('class', 'land')
.attr('d', path);
g.append('path')
.datum(topojson.mesh(state, state.objects.Sikkim, (a, b) => a !== b))
.attr('class', 'boundary')
.attr('d', path);
g.append("g")
.selectAll("path")
.data(topojson.feature(state, state.objects.Sikkim).features)
.enter()
.append("path")
.attr("d", path)
.attr("class","boundary")
//.on("mouseover", function(d)){
.on("click", function(d) {
var prop = d.properties;
var string = "<p><strong>District Name</strong>: " + prop.Dist_Name;
d3.select("#Place_Details")
.html("")
.append("text")
.html(string);
d3.select(this).attr("class","boundary hover");
})
//.on("mouseout"), function(d){
.on("click", function(d) {
d3.select("h2").text("");
d3.select(this).attr("class","boundary")
.attr("fill", "#ff1a75");
});
});
.columns {
float: left;
width: 50%;
}
/* Clear floats after the columns */
.mapcontainer:after {
content: "";
display: table;
clear: both;
}
svg {
background: #ffffff;
}
.land {
fill: #ff1a75;
}
.boundary {
fill: none;
stroke: #00ffff;
stroke-linejoin: round;
stroke-linecap: round;
stroke-width: 1px;
vector-effect: non-scaling-stroke;
}
h2 {
top: 50px;
font-size: 1.6em;
}
.hover {
fill: yellow;
}
<script src="https://d3js.org/d3.v5.min.js" charset="utf-8"></script>
<script src="https://unpkg.com/topojson@3" charset="utf-8"></script>
<div id="Sk_Map" style="width: 300px; float:left; height:450px; margin:5px"></div>
<div id="Place_Details" style="width: 400px; float:right; height:450px; overflow: auto; margin:5px"></div>
如何优化此代码?我希望为地图添加缩放功能,但现在我想显示区/县的名称。
【问题讨论】:
标签: javascript html css json d3.js