我尝试在底图(栅格图块)中渲染美国各州(矢量数据)的Map。Map还应该包括缩放,因为我计划添加不同县和其他边界类型的缩放转换。请原谅我的代码,因为我是一个真实的新手在JS/D3 JS。我在互联网上找到了一个很好的例子,我的代码基于它,我希望它是有意义的。
渲染栅格图块,但根本不渲染矢量数据。有人能帮帮我吗?我觉得我已经很接近了,谢谢:)
function testMap() {
var states = d3.json("https://cdn.jsdelivr.net/npm/us-atlas@3/states-10m.json").then(topology => topojson.feature(topology, topology.objects.states).features)
var width = window.innerWidth,
height = window.innerHeight;
var map = d3.select(".visualizations").append("div")
.attr("class", "map")
var layer = map.append("div")
.attr("class", "layer");
const svg = d3.select(".layer").append("svg")
.attr("width", width)
.attr("height", height);
var g = d3.select("svg").append("g")
const projection = d3.geoMercator()
.scale(1 / (2 * Math.PI))
.translate([0, 0]);
const render = d3.geoPath(projection);
const tile = d3.tile()
.extent([[0, 0], [width, height]])
.tileSize(512);
const zoom = d3.zoom()
.scaleExtent([1 << 10, 1 << 15])
.extent([[0, 0], [width, height]])
.on("zoom", ({transform}) => zoomed(transform));
let image = svg.append("g")
.attr("pointer-events", "none")
.selectAll("image");
var initialScale = 1 << 12
var initialCenter = [-98 - 35 / 60, 39 + 50 / 60]
svg
.call(zoom)
.call(zoom.transform, d3.zoomIdentity
.translate(width / 2, height / 2)
.scale(-initialScale)
.translate(...projection(initialCenter))
.scale(-1));
function zoomed(transform) {
const tiles = tile(transform);
image = image.data(tiles, d => d).join("image")
.attr("xlink:href", function (d) { return "http://" + "abc"[d[1] % 3] + ".tile.openstreetmap.org/" + d[2] + "/" + d[0] + "/" + d[1] + ".png"; })
.attr("x", ([x]) => (x + tiles.translate[0]) * tiles.scale)
.attr("y", ([, y]) => (y + tiles.translate[1]) * tiles.scale)
.attr("width", tiles.scale)
.attr("height", tiles.scale);
projection
.scale(transform.k / (2 * Math.PI))
.translate([transform.x, transform.y]);
svg.selectAll("path")
.data(states.features)
.enter()
.append("path")
.attr("class","mapFocus")
.attr("d", render)
// I tried the option below but does not work either
// path.attr("d", render(feature));
}
}
1条答案
按热度按时间oknwwptz1#
您可以尝试替换
zoomed
函数的代码。使用代码: