SOURCE

console 命令行工具 X clear

                    
>
console
const map = new mapboxgl.Map({
    container: 'map',
    zoom: 7,
    center: [119.3, 29.7],
    pitch: 0,
    bearing: 0,
    style: 'https://openmap.tech/styles/streets.json',
    hash: true
});

const wkt = new Wkt.Wkt();


map.on('load', function () {
    document.getElementById('hangzhou').addEventListener('click', () => {
        getData('浙江省杭州市')
    })

})

function getData(name) {
    fetch('https://ditu.zjzwfw.gov.cn/ime-server/rest/xzqh_zj/division/search?withgeometry=true&withparents=false&fullname=' + name).then(resp => resp.json()).then(resp => {
        const items = resp.result.children

        setButtons(items)
        setLayers(items)
    })
}

function setButtons(items) {
    document.getElementById('buttons').innerHTML = ''
    items.forEach(item => {
        createButton(item.NAME, item.FULLNAME)
    })
}

function createButton(name, fullname) {
    const btn = document.createElement('button')
    btn.className = 'button'
    const txt = document.createTextNode(name)
    btn.appendChild(txt)

    document.getElementById('buttons').appendChild(btn)
    btn.addEventListener('click', e => {
        getData(fullname)
    })
}

function getColor() {
    const getRandom = () => {
        return Math.floor(Math.random() * 256)
    }

    return `rgb(${getRandom()}, ${getRandom()}, ${getRandom()})`
}


function setLayers(items) {
    const data = {
        type: 'FeatureCollection',
        features: []
    }

    items.forEach(item => {
        const geometry = wkt.read(item.GEOMETRY).toJson()
        data.features.push({
            type: 'feature',
            properties: {
                color: getColor()
            },
            geometry
        })
    })

    const source = map.getSource('region')
    if (source) {
        source.setData(data)
        return
    }

    map.addSource('region', {
        type: 'geojson',
        data
    })

    map.addLayer({
        id: 'region',
        type: 'fill',
        source: 'region',
        paint: {
            'fill-color': ['get', 'color'],
            'fill-opacity': 0.6
        }
    })
}
<div id="map"></div>

<div class="buttons">
    <button class="button" id="hangzhou">杭州市 ^</button>
    <hr>
    <div id="buttons"></div>
</div>
#map {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    overflow: hidden;
}

.buttons {
    position: absolute;
    left: 10px;
    top: 10px;
}

.button {
    margin: 3px;
}

本项目引用的自定义外部资源