第八章 地图可视化
第一节
地理信息: Naturalearthdata
数据格式:
数据格式 | 特征 | 代码 |
GeoJSON | 最外层是Object,包括Geometry\Feature\FeatureCollection | {"type":"FeatureCollection","features":[{"type":"Feature","propeties":{"id":"110288","name":""密云县","cp":[117.0923,40,5121]...} |
TopoJSON | GeoJSON的扩展,边界线只记录一次,地理坐标使用整数 |
地图可视化API
案例:2016年中国各省GDP
<html>
<head>
<meta charset="utf-8">
<title>基于GeoJSON绘制中国GDP2016数据地图</title>
<style>
.province {
stroke: black;
stroke-width: 1px;
}
.southchinasea {
stroke: black;
stroke-width: 1px;
fill: red;
}
</style>
</head>
<body>
<script src="d3.v3.min.js" charset="utf-8"></script>
<script>
var width=(window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth)*0.98;
var height=(window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight)*0.98;
var gdp = [6790.32,2417.05,16803.12,10502.56,15717.27,23014.59,25979.82,22005.63,72812.55,
1026.39,9324.80,3702.76,2911.77,18021.86,12766.49,29550.19,28902.21,30053.10,13619.17,
29806.11,37002.16,28669.02,63002.33,16538.19,16723.78,70116.38,25123.45,42886.49,14063.13,17831.51,15083.67,1000,1000,1000];
var linear = d3.scale.linear()
.domain([990,90000])
.range([0,255]);
var mapcolor = new Array();
for(var i=0; i<34; i++){
mapcolor[i] = "#"+parseInt(255-linear(gdp[i])).toString(16)+"0000";
}
console.log(mapcolor);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
//定义地图的投影
var projection = d3.geo.mercator()
.center([107, 31])
.scale(550)
.translate([width/2, height/2]);
//定义地形路径生成器
var path = d3.geo.path()
.projection(projection); //设定投影
//请求china.geojson
d3.json("China.geojson", function(error, root) {
if (error)
return console.error(error);
console.log(root);
var groups = svg.append("g");
groups.selectAll("path")
.data(root.features)
.enter()
.append("path")
.attr("class","province")
.attr("fill", function(d,i){
return mapcolor[i];
})
.attr("d", path) //使用路径生成器
.on("mouseover",function(d,i){
d3.select(this)
.attr("fill","yellow");
})
.on("mouseout",function(d,i){
d3.select(this)
.attr("fill",mapcolor[i]);
});
var texts = svg.selectAll(".texts")
.data(root.features)
.enter()
.append("text")
.attr("class", "texts")
.text(function(d){return d.properties.name;})
.attr("transform", function(d) {
var centroid = path.centroid(d),
x = centroid[0],
y = centroid[1];
if((d.properties.name=="河北")||(d.properties.name=="澳门")||(d.properties.name=="安徽"))
y=y+25;
return "translate(" + x + ", " + y + ")";
})
.attr('fill','#AAA')
.attr("font-size","12px");
});
//请求southchinasea.svg
d3.xml("southchinasea.svg", function(error, xmlDocument) {
svg.html(function(d){
return d3.select(this).html() + xmlDocument.getElementsByTagName("g")[0].outerHTML;
});
d3.select("#southchinasea")
.attr("transform","translate(840,380)scale(0.5)")
.attr("class","southchinasea");
});
</script>
</body>
</html>
第二节 Echarts地图可视化
Echarts地图