d3加载geojson实现地图显示

2019-06-15 走过路过 3069 0

D3.js是最流行的可视化库之一,下面是一个d3加载geojson地图数据实现一个简单的地图显示demo。
官方地址:https://d3js.org/

1、首先引用d3库:<script src="d3.min.js"></script>
2、定义一个div显示地图:<div id="main">
3、js代码:json使用你自已的geojson数据
var json={"type":"FeatureCollection","features":[...]}

var width = 1600,height = 700;
var svg = d3.select("#main").append("svg").attr("width", width).attr("height", height);
var projection = d3.geoMercator().fitSize([width, height], json);
var path = d3.geoPath(projection);

svg.selectAll("path")
    .data( json.features )
    .enter()
    .append("path")
    .attr("stroke","#000")
    .attr("stroke-width",1)
	.attr("d", path)
	.attr("fill", function(d,i){
		if(d.geometry.type == 'Polygon') {
			return d.properties.fill || "#555555";
		} else {
			return 'none';
		}
		
	})
	.on("mouseover",function(d,i){
		if(d.geometry.type == 'Polygon') {
			d3.select(this)
			.attr("fill","yellow");
			
			d3.select("#tooltip").transition().duration(200).style("opacity", .9);

			d3.select("#tooltip").html(tooltipHtml(d.properties.id))
			 .style("left", (d3.event.pageX) + "px")
			 .style("top", (d3.event.pageY) + "px");
		} 
		
	})
	.on("mouseout",function(d,i){		
		if(d.geometry.type == 'Polygon') {
			d3.select(this)
			.attr("fill",d.properties.fill || "#555555");
			d3.select("#tooltip").transition().duration(500).style("opacity", 0);
		} 			
		
	});

function tooltipHtml(m){    
	 return "<h4>"+m+"</h4><table>"+
		 "<tr><td>Low</td><td>test</td></tr>"+
		 "<tr><td>Average</td><td>test</td></tr>"+
		 "<tr><td>High</td><td>test</td></tr>"+
		 "</table>";
}

相关推荐
全部评论 最新评论 最早评论
还没有用户评论

联系我们

微信公众号
打赏作者