欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

d3之画地图

程序员文章站 2022-03-14 15:53:20
...

目录

画一个简单的地图,基于GeoJSON数据

    var color = d3.scale.category20();
    //定义地图的投影
    var projection = d3.geo.mercator()
        .center([107,31])
        .scale(600)
        .translate([width/2,height/2]);
    //定义地理路径生成器
    var path = d3.geo.path()
        .projection(projection);

    var groups = svg.append("g");
    //读取地图数据,并且把它画出来
    d3.json("china.geojson",function(error,root){
        if(error)
            return console.error(error);
        groups.selectAll("path")
            .data(root.features)
            .enter()
            .append("path")
            .attr("class","province")
            .style("fill",function(d,i){
                return color(i);
            })
            .attr("d",path)
            .on("mouseover",function(d,i){
                d3.select(this)
                    .style("fill","yellow");
            })
            .on("mouseout",function(d,i){
                d3.select(this)
                    .style("fill",color(i));
            });
    })

基于TopoJSON数据,相邻省份的交互

d3.json("data/china.topojson",function(error,toporoot){
    if(error)
        return console.error(error);
    var georoot = topojson.feature(toporoot,toporoot.objects.china);

    var neighbors = topojson.neighbors(
        toporoot.objects.china.geometries);

    var groups = svg.append("g");

    var paths = groups.selectAll("path")
        .data(georoot.features)
        .enter()
        .append("path")
        .attr("class","province")
        .style("fill","#ccc")
        .attr("d",path);
    paths.each(function(d,i){
        d.neighbors = d3.selectAll(
            neighbors[i].map(function(j){
                return paths[0][j];
            })
        );
    })
    .on("mouseover",function(d,i){
        d3.select(this).style("fill","red");
        d.neighbors.style("fill","steelblue");
    })
    .on("mouseout",function(d,i){
        d3.select(this).style("#ccc");
        d.neighbors.style("fill","#ccc");
    });


});
相关标签: color