在map上标记point

先说下最近学习的一些经验,
1越来越觉得我们在学习每个东西的时候应该打破砂锅问到底,为什么要这样做?这样做有什么用?在网页上呈现的是什么?将每句代码的作用都搞清楚,这样才能在组合的时候我们能用的很放心。
2.还要一个就是数据格式的问题,在学习别人代码的时候要搞清楚别人加载的文件数据格式是什么,其实在加载完数据后,作者操作的本质就是不断提取加载的数据,组合成自己所需要的数据格式,在地图中这一点尤为重要,比如说path,我们需要geo形式的数据,但是我们只要topojson格式,所以就需要转换一下了。
3.在学习时理解第一,记忆第二,对代码的每句作用进行肢解,试着总体上还原整篇代码的写作策略,然后自己写,不要对着别人的敲,自己试着把思路过一遍敲出来,不会的跳过去,一遍完整下来再去调试修改。

<style type="text/css">
    circle {
        fill:red;
    }
    path.province{
        /*stroke: pink;*/

    }
</style>
<body>

</body>
<script type="text/javascript">
    var width=1000,height=1000;
    var svg=d3.select("body")
              .append("svg")
              .attr("width",width)
              .attr("height",height)
//geo是三维的,需要转换为二维的,所以需要定义投影方式
    var projection=d3.geo.mercator()
                         .center([107,31])
                         .scale(800)
                         .translate([width/2,height/2])

    var path=d3.geo.path().projection(projection)

    d3.json("china.topojson",function(error,toporoot){
    //将topojson转换为geojson   需要额外mike提供的js文件
        var georoot = topojson.feature(toporoot,toporoot.objects.china);

        var china=svg.append("g")
        var province=svg.selectAll("path .province")
                        .data(georoot.features)
                        .enter()
                        .append("path")
                        .attr("class","province")
                        .style("fill","steelblue")
                        .attr("d",path)

        d3.json("places.json",function(error,root){
        //将g元素移动到点所在的位置
            var points=svg.selectAll("g .circle")
                           .data(root.location)
                           .enter()
                           .append("g")
                           .attr("class","circle")
                           .attr("transform",function(d,i){
                                var d=projection([d.log,d.lat])
                                return  "translate("+d[0]+","+d[1]+")";
                           })
                points.append("circle")
                           .attr("r",7)
            points.append("image")
                  .attr("x",-20)
                  .attr("y",20)
                  .attr("width",60)
                  .attr("height",60)
                  .attr("xlink:href",function(d){
                        return d.img;
                  })
        })

    })
</script>

这篇代码总体思路:
1.先画出china
1)因为geo三维,所以定义projection转换二维
2)绑定geo.path生成地图
2.circle
1)将g元素移动到特定位置
2)g元素中添加circle
3)g元素中添加image标签
下边是point的数据格式
这里写图片描述
下图是转换后georoot的数据,我们可以看到features中包含了34个省的数据
这里写图片描述

最后效果这里写图片描述

posted @ 2017-10-10 16:03  Braveliberty  阅读(205)  评论(0编辑  收藏  举报