v4.x 版本-中国地图
代码是基于vue 2.x版本项目中,代码注释部分为关键点解释都是基于d3-v4.x版本的。
demo实现效果图如下:
每个省可进行点击(获得该省的详细信息),鼠标悬浮在哪个省之上,会使该省高亮。
实现代码如下:(包含关键代码注释)
<template>
<div class="hello">
</div>
</template>
<script src="//d3js.org/topojson.v1.min.js"></script>
<script>
const d3 = require("d3");
const axios = require("axios");
// import * as d3 from "d3"
export default {
name: "china",
data() {
return {
};
},
mounted: function() {
this.$nextTick(function() {
var width = 800,
height = 600;
var svg = d3
.select("body")
.append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(0,0)");
var projection = d3
.geoMercator()
.center([107, 31])
.scale(600)
.translate([width / 2, height / 2]);
var path = d3.geoPath().projection(projection);
var color = d3.schemeCategory10;
var url = "../../static/china.geojson";
d3.json(url).then(function(root) {
svg
.selectAll("path")
.data(root.features)
.enter()
.append("path")
.attr("stroke", "#000")
.attr("stroke-width", 1)
.attr("fill", function(d, i) {
return color[i % 10];
})
.attr("d", path)
.on("mouseover", function(d, i) {
d3.select(this).attr("fill", "yellow");
})
.on("mouseout", function(d, i) {
d3.select(this).attr("fill", color[i % 10]);
})
.on("click", function(d) {
// console.log(d);
//计算面积、中心、边界框
var area = path.area(d);
var centroid = path.centroid(d);
var bounds = path.bounds(d);
//输出到控制台
console.log("省份:" + d.properties.name);
console.log("面积:" + area);
console.log("中心:" + centroid);
console.log("边界框:");
console.log(bounds);
//显示中心
svg
.append("circle")
.attr("class", "centroid")
.attr("cx", centroid[0])
.attr("cy", centroid[1])
.attr("r", 8);
//显示边界框
svg
.append("rect")
.attr("class", "boundingbox")
.attr("x", bounds[0][0])
.attr("y", bounds[0][1])
.attr("width", bounds[1][0] - bounds[0][0])
.attr("height", bounds[1][1] - bounds[0][1])
.attr("fill", "none")
.attr("stroke-width", "1px")
.attr("stroke", "blue");
});
});
//请求southchinasea.svg
// d3.xml("../../static/southchinasea.svg").then(function(xmlDocument) {
// console.log( xmlDocument)
// svg.html(function(d) {
// return (
// d3.select(this).html() +
// xmlDocument.getElementsByTagName("g")[0].outerHTML
// );
// });
// d3
// .select("#southchinasea")
// .attr("transform", "translate(540,410)scale(0.5)")
// .attr("class", "southchinasea");
// });
});
},
};
</script>