我使用了 Bostock 等人的一些代码,并进行了一些编辑,以便您输入焦点地理区域界限(十进制坐标):
var WNES = { "W": 67.0, "N":37.5, "E": 99.0, "S": 5.0 };
和目标 svg 画布'width(px) 例如:
var width = 600,
自动设置 svg 画布'height, the 变焦比例, and 译文以便将显示仅集中并完全集中在目标地理区域上。
// 1. -------------- SETTINGS ------------- //
// India geo-frame borders (decimal ⁰)
var WNES = { "W": 67.0, "N":37.5, "E": 99.0, "S": 5.0 };
// Geo values of interest :
var latCenter = (WNES.S + WNES.N)/2, // will not be used
lonCenter = (WNES.W + WNES.E)/2, // will not be used
geo_width = (WNES.E - WNES.W),
geo_height= (WNES.N - WNES.S);
// HTML expected frame dimensions
var width = 600,
height = (geo_height / geo_width) * width ; // height function of width with ratio of geo-frame (later requires equirectangular projection!)
// Projection: projection, reset scale and reset translate
var projection = d3.geo.equirectangular()
.scale(1)
.translate([0, 0]);
// Normal stuff: SVG injection:
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
// Normal stuff: Path
var path = d3.geo.path()
.projection(projection)
.pointRadius(4);
// Data (getJSON: TopoJSON)
d3.json("final.json", showData);
// 2. ---------- FUNCTION ------------- //
function showData(error, fra) {
var Levels = topojson.feature(fra, fra.objects.levels);
// Focus area box compute to derive scale & translate.
var b = path.bounds(Levels), // get data's bounds as [[left, bottom], [right, top]] [[W, S], [E, N]]
s = 1 / Math.max((b[1][0] - b[0][0]) / width, (b[1][1] - b[0][1]) / height),
t = [(width - s * (b[1][0] + b[0][0])) / 2, (height - s * (b[1][1] + b[0][1])) / 2];
// Projection update
projection
.scale(s)
.translate(t);
//Normal stuff: Append my topojson objects => svg layers
svg.append("path")
.datum(Levels)
.attr("d", path)
svg.selectAll(".levels")
.data(topojson.feature(fra, fra.objects.levels).features)
.enter().append("path")
.attr("class", function(d) { return "Topo_" + d.properties.name; })
.attr("data-elev", function(d) { return d.properties.name; })
.attr("d", path)
}
结果很完美:
See:
路径.边界(特征) https://github.com/mbostock/d3/wiki/Geo-Paths#wiki-path_bounds-- 计算指定要素的投影边界框(以像素为单位)。
具有自动对焦功能的印度地形图 http://bl.ocks.org/hugolpz/6310180(Hugo Lopez) -- 工作示例(具有自定义画布高度)
给定 geoJSON 对象,在 d3 中将地图居中 https://stackoverflow.com/questions/14492284/(Bostock 等人)——来自那里的关键帮助
投影到边界框 http://bl.ocks.org/mbostock/4707858(Mike Bostock) -- 工作示例(带有前缀画布尺寸)
D3js:如何设计地形图? https://stackoverflow.com/questions/18300527/(Hugo Lopez) -- 使用 makefile 和 html-d3js 代码的教程。