天地图 + geojson 绘制 行政区划边界

发布时间 2023-09-07 14:41:54作者: loganfan

 geojson数据来源 阿里云geojson

源码

<!DOCTYPE html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge">
    <title>天地图-地图API-范例-加载geojson数据</title>
    <style type="text/css">
        html {
            height: 100%
        }
 
        body {
            height: 100%;
            margin: 0;
            padding: 0
        }
 
        #map-canvas {
            height: 100%;
            fill: #000000;
        }
    </style>
</head>
<body>
    <button onclick="remove()">remove</button>
<div id="map-canvas"></div>
<script src=" http://api.tianditu.gov.cn/api?v=4.0&tk=f5f540e277f65383edab9a2804e7eb2d" type="text/javascript"></script>
<script src="http://cdn.bootcss.com/d3/3.5.17/d3.js " charset="utf-8"></script>
<script src="http://lbs.tianditu.gov.cn/api/js4.0/opensource/openlibrary/D3SvgOverlay.js"></script>
<script>
    var countries = [];
    var countriesOverlay = new T.D3Overlay(init,redraw);
 
    var map = new T.Map("map-canvas");
    map.centerAndZoom(new T.LngLat(116.39769, 40.25945), 6)
    d3.json("/assets/100000_full.json", function (data) {
        countries = data.features;
        map.addOverLay(countriesOverlay)
        countriesOverlay.bringToBack();
    });
 
    function init(sel, transform) {
        var upd = sel.selectAll('path.geojson').data(countries);
        upd.enter()
            .append('path')
            .attr("class", "geojson")
            .attr('stroke', 'blue')
            .attr('stroke', 'blue')
            .attr('stroke-width', '2px')
            //.attr('fill', 'none') //不填充
            .attr('fill', function (d, i) {
                return d3.hsl(Math.random() * 360, 0.9, 0.5)
            }) //填充
            .attr('fill-opacity', 0.5) //填充透明度
    }
 
    function redraw(sel, transform) {
        sel.selectAll('path.geojson').each(
            function (d, i) {
                d3.select(this).attr('d', transform.pathFromGeojson)
                    .on("mouseover",function(){
                        console.log('这是点击了',);
                    })
            }
        )
    }

    function remove(){
        d3.selectAll('path.geojson').remove()
    }
</script>
 
</body>
</html>