Leaflet_D3:点

开发环境

npm install leaflet d3 --save

- leaflet v1.x
- d3 v4.x

根据d3创建svg,并添加到map地图的overlayPane下

 var svg = d3.select(mymap.getPanes().overlayPane).append('svg'),
        g = svg.append('g').attr('class', 'leaflet-zoom-hide'); 

注册map zoom 事件

mymap.on('zoom', adjustCircle); 

示例代码

<!DOCTYPE html>
<html> 
<head>
    <title>d3_leaflet_1</title>
</head>
<link rel="stylesheet" type="text/css" href="node_modules/leaflet/dist/leaflet.css">
<script type="text/javascript" src="node_modules/leaflet/dist/leaflet.js"></script>
<script type="text/javascript" src="node_modules/d3/build/d3.js"></script>
<style>
    html,
    body {
        margin: 0;
        padding: 0;
    } 
    #map {
        width: 100%;
        height: calc(100vh)
    }
</style>

<body>
    <div id="map"></div>
    <script type="text/javascript">
        var mymap = L.map('map').setView([29, 125.77], 6);
        L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {

            maxZoom: 18,
            noWrap: true
        }).addTo(mymap);


        var svg = d3.select(mymap.getPanes().overlayPane).append('svg');
        g = svg.append('g').attr('class', 'leaflet-zoom-hide'); 

        mymap.on('zoom', adjustCircle); 

        function drwaCircle() { 
            d3.json("data/circles.json", function (collection) {
                var latLngs = [];
                collection.objects.forEach(function (d) {
                    latLngs.push([d.circle.coordinates[0], d.circle.coordinates[1]]);
                })

                console.log(latLngs);
                var c = g.selectAll('circle')
                    .data(latLngs);

                var cAttr = c.enter()
                    .append('circle')
                    .style("stroke", "black")
                    .style("fill", "yellow")
                    .attr('r', 2 * (mymap.getZoom() == 0 ? 1 : mymap.getZoom()))
                    .attr("cx", function (p) {
                        console.log("p", p)
                        return mymap.latLngToLayerPoint([p[0], p[1]]).x
                    })
                    .attr("cy", function (p) {
                        return mymap.latLngToLayerPoint([p[0], p[1]]).y
                    })
            })
        } 
        function adjustCircle() {
            d3.selectAll("circle")
                .attr('r', 2 * (mymap.getZoom() == 0 ? 1 : mymap.getZoom()))
                .attr('cx', o => mymap.latLngToLayerPoint([o[0], o[1]]).x)
                .attr('cy', o => mymap.latLngToLayerPoint([o[0], o[1]]).y);
        } 
        function initial() { 
            svg.attr("width", 1500)
                .attr("height", 800);
            drwaCircle();
        }
        initial()
    </script>
</body> 
</html>

更多内容,欢迎关注公众号

5310582-3cf76fa57d99fb99.jpg
seeling_GIS

转载自:https://blog.csdn.net/weixin_34248023/article/details/88149667

You may also like...