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: "world",
data() {
return {
};
},
mounted: function() {
this.$nextTick(function() {
// // 球形世界地区
// var width = 800,
// height = 400;
// var svg = d3
// .select("body")
// .append("svg")
// .attr("width", width)
// .attr("height", height);
// var ortho = d3
// .geoOrthographic()
// .scale(130)
// .translate([width / 2, height / 2])
// .rotate([60, 0, 0])
// .clipAngle(90);
// var path = d3.geoPath().projection(ortho);
// var graticule = d3
// .geoGraticule()
// .extent([[-180, -90], [180, 90]])
// .step([10, 10]);
// svg
// .append("path")
// .attr("class", "graticule")
// .attr("d", path(graticule()));
// var color = d3.schemeCategory10;
// var url = "../../static/world.json";
// d3.json(url).then(function(root) {
// var groups = svg.append("g");
// groups
// .selectAll("path")
// .data(root.features)
// .enter()
// .append("path")
// .attr("class", "country")
// .attr("d", path)
// .style("fill", function(d, i) {
// return color[i%10];
// });
// });
// return; //球形世界地区到此处结束
//等距圆通投影
var width = 1000,
height = 600;
var svg = d3
.select("body")
.append("svg")
.attr("width", width)
.attr("height", height);
var projection = d3
.geoEquirectangular()
// .center([116.38, 39.93]) 以北京为中心
// .scale(80)
.translate([width / 2, height / 2]);
//地理路径生成器
var path = d3.geoPath().projection(projection);
var color = d3.schemeCategory10;
//圆生成器
var geocircle = d3.geoCircle();
var url = "../../static/world.json";
d3.json(url).then(function(root) {
var groups = svg.append("g");
groups
.selectAll("path")
.data(root.features)
.enter()
.append("path")
.attr("class", "country")
.style("fill", function(d, i) {
return color[i % 10];
})
.attr("d", path);
svg
.append("rect")
.attr("class", "border")
.attr("x", 0)
.attr("y", 0)
.attr("width", width)
.attr("height", height)
.attr("fill", "none");
svg
.append("line")
.attr("class", "axis")
.attr("x1", 0)
.attr("y1", height / 2)
.attr("x2", width)
.attr("y2", height / 2)
.attr("fill", "none");
svg
.append("line")
.attr("class", "axis")
.attr("x1", width / 2)
.attr("y1", 0)
.attr("x2", width / 2)
.attr("y2", height)
.attr("fill", "none");
// var washington = projection([-77.04, 38.91]); //获取华盛顿的投影坐标
// svg
// .append("circle")
// .attr("cx", washington[0])
// .attr("cy", washington[1])
// .attr("r", 10)
// .style("fill", "red");
// var pos = projection.invert(washington);
// console.log(pos); //输出[-77.04, 38.91]
});
});
},
};
</script>