Skip to content

Instantly share code, notes, and snippets.

@rogeriojlle
Last active June 17, 2020 01:10
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save rogeriojlle/d13d1ad1eb25aff49d2d6908003d48fe to your computer and use it in GitHub Desktop.
retorna a imagem svg do municipio consultando a api de malhas do IBGE
/*
* o paramentro "municipio" é o codigo dele, que pode ser obtido em:
* https://servicodados.ibge.gov.br/api/docs/localidades?versao=1#api-bq
*/
async function municipioSVG (municipio) {
const codEstado = municipio.toString().substring(0, 2)
const div = document.createElement('div')
const response = await fetch(
`https://servicodados.ibge.gov.br/api/v2/malhas/${codEstado}?resolucao=5&formato=image/svg+xml`
)
div.innerHTML = await response.text()
const paths = [...div.querySelectorAll(`svg path.C${municipio}`)]
const comprimentos = paths.map(p => Math.floor(p.getTotalLength()))
const pontosSvg = comprimentos.map((c, i) => {
const arr = [...Array(c).keys()]
arr.push(c)
return arr.map(p => paths[i].getPointAtLength(p))
}).flat()
const setX = new Set(pontosSvg.map(({ x }) => x))
const setY = new Set(pontosSvg.map(({ y }) => y))
const vbX = Math.min(...setX)
const vbY = Math.min(...setY)
const vbWidth = Math.max(...setX) - vbX
const vbHeight = Math.max(...setY) - vbY
const svg = document.createElementNS('http://www.w3.org/2000/svg','svg')
svg.setAttribute('viewBox', `${vbX} ${vbY} ${vbWidth} ${vbHeight}`)
for (let path of paths) {
svg.appendChild(path)
}
return svg
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment