如何在D3.js绘制的美国州级地图上展示经纬度点位?
解决D3.js美国地图上绘制经纬度点位的问题
要在已绘制的美国州级地图上展示经纬度点位,核心是利用D3的投影函数将地理坐标转换为SVG画布上的像素坐标,以下是具体修改方案:
关键修改步骤
定义Albers USA投影
us-atlas提供的州数据采用Albers USA投影,因此需要创建对应投影实例,并调整缩放与偏移以适配你的SVG尺寸:const projection = d3.geoAlbersUsa() .scale(1200) // 调整缩放比例让地图适配宽高 .translate([w / 2, h / 2]); // 将地图中心移到SVG画布中央关联投影到geoPath
绘制州边界时,需要把投影传入d3.geoPath(),确保地图使用正确的投影规则:const path = d3.geoPath().projection(projection); // 后续绘制path时使用这个path变量 .attr("d", path)绘制点位
利用投影函数将每个地点的经纬度转换为SVG坐标,然后绘制圆形标记:svg.append("g") .attr("class", "locations") .selectAll("circle") .data(locations) .join("circle") .attr("cx", d => projection([d.long, d.lat])[0]) .attr("cy", d => projection([d.long, d.lat])[1]) .attr("r", 5) // 圆点半径,可按需调整 .style("fill", "blue") .style("stroke", "white") // 可选:添加白色描边让圆点更醒目 .style("stroke-width", 1);
修改后的完整代码
(async function getMapData() { const DATA_URL = "https://cdn.jsdelivr.net/npm/us-atlas@3/states-albers-10m.json"; let resp = await fetch(DATA_URL); const topoJson = await resp.json(); const geoJson = await topojson.feature(topoJson, topoJson.objects.states).features await drawMap(geoJson); console.log("Done"); })(); async function drawMap(data) { const w = 1000; const h = 800; // 定义Albers USA投影 const projection = d3.geoAlbersUsa() .scale(1200) .translate([w / 2, h / 2]); // 创建关联投影的geoPath const path = d3.geoPath().projection(projection); const svg = d3.select("body") .append("svg") .attr("width", w) .attr("height", h); svg.append("g") .selectAll("path") .data(data) .join("path") .attr("d", path) // 使用带投影的path .style("fill", "#f0f0f0") // 可选:给州添加填充色,让点位更明显 .style("stroke", "black") .style("stroke-width", "1px"); const locations = [ { long: -73.9249, lat: 40.6943 }, { long: -118.4068, lat: 34.1141 }, { long: -96.7667, lat: 32.7935 } ]; // 绘制点位 svg.append("g") .attr("class", "locations") .selectAll("circle") .data(locations) .join("circle") .attr("cx", d => projection([d.long, d.lat])[0]) .attr("cy", d => projection([d.long, d.lat])[1]) .attr("r", 5) .style("fill", "blue") .style("stroke", "white") .style("stroke-width", 1); }
.locations circle { fill: blue; }
<script src='https://d3js.org/d3.v6.min.js'></script> <script src="https://unpkg.com/topojson@3"></script>
说明
- 投影的
scale值可根据实际需求调整,确保地图在SVG画布中显示合适。 - 如果部分点位显示异常,需检查经纬度格式是否正确(D3投影接受的是
[经度, 纬度]数组)。
内容的提问来源于stack exchange,提问作者prasad_
相关产品推荐
相关产品推荐

