d3之画地图

目录

画一个简单的地图,基于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");
    });


});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值