Skip to content

Instantly share code, notes, and snippets.

@mbarker84
Last active January 17, 2025 17:05
Show Gist options
  • Save mbarker84/de0f5493a3d7b69f656682f9724b34d2 to your computer and use it in GitHub Desktop.
Save mbarker84/de0f5493a3d7b69f656682f9724b34d2 to your computer and use it in GitHub Desktop.
create-map-svg
import { geoPath, geoIdentity } from 'd3'
import { writeFile } from 'node:fs/promises'
import { stat } from 'node:fs'
const geojsonUrl = 'https://assets.codepen.io/85648/map-example.json'
const dimensions = {
width: 600,
height: 300,
}
fetch(geojsonUrl)
.then((response) => response.json())
.then(async (data) => {
try {
console.log('✨Generating SVG')
const { width, height } = dimensions
const projection = geoIdentity()
.reflectY(true) // SVG co-ordinate system is the opposite way up, so we need to flip it
.fitSize([dimensions.width, dimensions.height], data) // Scale to fit our SVG dimensions
const path = geoPath(projection)
const paths = data.features.map((d) => {
return `<path id="${d.properties.name}" d="${path(d)}" />`
})
const fileData = `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">
${paths.join('')}
</svg>`
await writeFile('./src/map-svg.svg', fileData)
/* Output the file size, for info */
stat(outputPath, (err, stats) => {
console.log(
'Done!',
`Size ${parseFloat(stats.size / BYTES_PER_MB).toFixed(2)}MB`
)
})
} catch (error) {
console.error('Error writing file')
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment