【发布时间】:2019-03-08 06:20:27
【问题描述】:
我正在构建一个 Web 应用程序来显示世界各国之间的不同趋势和统计数据。使用 d3,我可以加载 topojson 文件并投影世界地图。
var countryStatistics = [];
var pathList = [];
function visualize(){
var margin = {top: 100, left: 100, right: 100, bottom:100},
height = 800 - margin.top - margin.bottom,
width = 1200 - margin.left - margin.right;
//create svg
var svg = d3.select("#map")
.append("svg")
.attr("height", height + margin.top + margin.bottom)
.attr("width", width + margin.left + margin.right)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
//load topojson file
d3.queue()
.defer(d3.json, "world110m.json")
.await(ready)
var projection = d3.geoMercator()
.translate([ width / 2, height / 2 ])
.scale(180)
//pass path lines to projection
var path = d3.geoPath()
.projection(projection);
function ready (error, data){
console.log(data);
//we pull the countries data out of the loaded json object
countries = topojson.feature(data, data.objects.countries).features
//select the country data, draw the lines, call mouseover event to change fill color
svg.selectAll(".country")
.data(countries)
.enter().append("path")
.attr("class", "country")
.attr("d", path)
.on('mouseover', function(d) {
d3.select(this).classed("hovered", true)
//this function matches the id property in topojson country, to an id in (see below)
let country = matchPath(this.__data__.id);
console.log(country)
})
.on('mouseout', function(d) {
d3.select(this).classed("hovered", false)
})
//here I push the country data into a global array just to have access and experimentalism.
for (var i = 0; i < countries.length; i++) {
pathList.push(countries[i]);
}
}
};
matchPath() 函数用于允许我将路径数据匹配到 countryStatistics 以在某个国家/地区被鼠标悬停时显示。
function matchPath(pathId){
//to see id property of country currently being hovered over
console.log("pathID:" + pathId)
//loop through all countryStatistics and return the country with matching id number
for(var i = 0; i < countryStatistics.length; i++){
if(pathId == countryStatistics[i].idTopo){
return countryStatistics[i];
}
}
}
问题:这是可行的,但仅限于一个方向。我可以从每个 topojson 路径获取我的统计数据……但我无法根据数据获取和操作各个路径。
我想要做的是有一个按钮,可以从 countryStatistics 中选择某个属性,并根据数据值构建域/范围比例并设置颜色渐变。我坚持的步骤是获取统计数据和路径数据接口。
我看到了两种可能的解决方案,
1:有一种方法可以在渲染过程中将拓扑路径数据连接到统计数据,我可以调用一个函数来重绘sgv...
2:我构建了一个包含所有路径数据和统计数据的新对象。在这种情况下,我可以只提取 topojson.objects.countries 数据而忽略其余数据吗?
我应该如何做到这一点?任何指针,下一步将不胜感激。
(我在这个项目中所处的位置...http://conspiracytime.com/globeApp)
【问题讨论】:
标签: javascript d3.js topojson