Published
Edited
Jun 28, 2021
2 forks
7 stars
Insert cell
md` # Rendering TopoJSON of South Korea with D3 v5`
Insert cell
topoData = await FileAttachment("topoKorea.json").json()
Insert cell
geoJson = topojson.feature(topoData, topoData.objects.skorea_provinces_2018_geo)
Insert cell
renderData = ({
width: 500,
height: 500,
margin: 50,
})
Insert cell
{
const svg = d3
.create('svg')
.attr('width', renderData.width)
.attr('height', renderData.height);

const clippedWidth = renderData.width - renderData.margin * 2;
const clippedHeight = renderData.height - renderData.margin * 2;

const geoMercator = d3
.geoMercator()
// the center uses longtitude and latitude
// get Long/Lat data from google maps
.center([128, 36])
.fitSize([clippedWidth, clippedHeight], geoJson);

const pathGen = d3.geoPath(geoMercator);

const stage = svg
.append('g')
.attr('transform', `translate(${renderData.margin},${renderData.margin})`);

const textX = 10;
const textY = 10;
const infoText = stage
.append('g')
.attr('transform', `translate(${textX},${textY})`)
.append('text');
infoText.text('no data');

const onMouseHover = d => {
stage
.selectAll('.geopath')
.filter(td => td.properties.name === d.properties.name)
.attr('fill', 'red');
infoText.text(d.properties.name);
};

const onMouseLeave = d => {
stage
.selectAll('.geopath')
.filter(td => td.properties.name === d.properties.name)
.attr('fill', 'gray');
infoText.text('선택 안함');
};

const tEnter = enter =>
enter
.append('path')
.attr('d', pathGen)
.attr('stroke', 'black')
.attr('fill', 'gray')
.classed('geopath', true)
.on('mouseenter', onMouseHover)
.on('mouseleave', onMouseLeave);
const tUpdate = null;
const tExit = null;
stage
.selectAll('.geopath')
.data(geoJson.features)
.join(tEnter, tUpdate, tExit);

return svg.node();
}
Insert cell
topojson = require('topojson@v3.0.2')
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more