我正在使用地图,我可以选择访问全球的地区(州/省)。我发现了很棒的乐器:d3.js和topojson。基于Mike Bostock’s examples我创建了一个精彩的地图,但我遇到了缩放性能问题。我理解转换需要很长时间才能有这样的情况,我有很多路径元素,但我希望这是一个更好的解决方案。
那么,是否可以通过d3.js + topojson修复它?
或者我应该更改视图并查看基于图块的地图吗?
谢谢!
var width = window.innerWidth;
var height = window.innerHeight;
var worldGeoJson = "https://gist.githubusercontent.com/mrandreev/e03a6d104e5d17ef5f5138e1b36a4c1e/raw/804030989ea94f13de6b4917ddcc429f6268020c/world.json";
var projection = d3.geo.patterson()
.scale(210)
.rotate([-11, 0])
.translate([width / 2, height / 2])
.precision(.1);
var path = d3.geo.path().projection(projection);
var zoom = d3.behavior.zoom()
.scaleExtent([1, 50])
.size([width, height])
.on("zoom", onZoom);
var svg = d3.select("#map")
.append("svg")
.attr("viewBox", "0 0 " + width + " " + height)
.attr("width", width)
.attr("height", height)
.call(zoom);
var g = svg.append("g");
d3.json(worldGeoJson, function(error, world) {
if (error) return console.error(error);
g.append("g")
.attr("class", "land")
.selectAll("path")
.data(topojson.feature(world, world.objects.states).features)
.enter().append("path")
.attr("d", path)
.append("title")
.text(function(d) {
return d.properties.name;
});
g.append("path")
.datum(topojson.mesh(world, world.objects.states, function(a, b) {
return a.properties.countryCode !== b.properties.countryCode;
}))
.attr("class", "country")
.attr("d", path);
g.append("path")
.datum(topojson.mesh(world, world.objects.states, function(a, b) {
return a.properties.countrycode === b.properties.countrycode && a !== b;
}))
.attr("class", "region")
.attr("d", path);
});
function onZoom() {
var t = d3.event.translate;
var s = d3.event.scale;
t[0] = Math.max(Math.min(t[0], 0), width * (1 - s));
t[1] = Math.max(Math.min(t[1], 0), height * (1 - s));
zoom.translate(t);
g.style("stroke-width", 1 / s)
.attr("transform", "translate(" + t + ")scale(" + s + ")");
}

.land {
fill: #222;
}
.land:hover {
fill: orange;
}
.country {
fill: none;
stroke: #fff;
stroke-width: .5px;
pointer-events: none;
}
.region {
fill: none;
stroke: #fff;
stroke-width: .2px;
stroke-opacity: .25;
pointer-events: none;
}

<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://d3js.org/topojson.v1.min.js"></script>
<script src="http://d3js.org/d3.geo.projection.v0.min.js"></script>
<div id="map"></div>
</body>
&#13;