zoukankan      html  css  js  c++  java
  • 用d3制作一个基于GeoJSON的中国地图

    基础知识

    地图数据

    数据格式有两种:GeoJSON,TopoJSON。其中,GeoJSON是描述地理信息的一种基本格式,TopoJSON是作者制定的格式。我主要了解GeoJSON。

    获取数据

    可自行百度
    中国的数据chain.geo.json放在附录里面

    示例

    {
    	"type": "FeatureCollection",
    	"features": [
            {
    			"type": "Feature",
    			"id": "shang_hai",
    			"properties": {
    				"name": "上海",
    				"cp": [121.4648, 31.2891],
    				"childNum": 19
    			},
    			"geometry": {
    				"type": "Polygon",
    				"coordinates": [[[120.9375, 31.0254],[121.2012, 31.4648],
    				[121.377, 31.5088],[121.1133, 31.7285],[121.2012, 31.8604],[121.9922, 31.5967],
    				[121.9043, 31.1572],[121.9922, 30.8057],[121.2891, 30.6738],[120.9375, 31.0254]
    					]
    				]
    			}
    		}, {
    			"type": "Feature",
    			"id": "xiang_gang",
    			"properties": {
    				"name": "香港",
    				"cp": [114.2578, 22.3242],
    				"childNum": 1
    			},
    			"geometry": {
    				"type": "Polygon",
    				"coordinates": [.....]
    			}
    		},
    		......
    		]
    		"srcSize": {
    		"left": 243.4766,
    		"top": 36.4307,
    		"width": 61.6113,
    		"height": 35.4638
    	}
    }
    

    GeoJSON数据解释

    它是用于描述地理空间信息的数据格式

    • FeatureCollection:特征集合
    • type:GeoJSON对象都有type属性,type的值有多种
    • Feature:是type的值之一,Feature特征对象必须包含变量geometry,properties
    • geometry:几何体
    • properties:值可以是任意JSON对象或null
    • Polygon:面
      所以china.geo.json文件里,有一个对象,该对象的type值为特征集合FeatureCollection,其成员Feature的每一项描述一个省的地理信息,特征对象properties里面包含该省的名称,id号。geometry包含该省的地理信息。

    地图制作

    在一个矩形区域中,划伤中国大陆和港澳台,再在矩形的右下角添加一个小框,里面绘制南海诸岛。南海岛屿需要单独制作。

    基础图像

    <!DOCTYPE html>
    <html>
    	<head>
    		<meta charset="utf-8">
    		<title>中国地图</title>
    		<script src="http://d3js.org/d3.v3.min.js"></script>
    	</head>
    	<body>
    		<svg></svg>
    	</body>
    	<script>
    		var width = 1000, height = 700;
    		//1.定义投影和生成器
    		//定义地图投影
    		var projection=d3.geo.mercator()
    		.center([107,31]) //地图中心位置,107是经度,31是纬度
    		.scale(600) //设置缩放量
    		.translate([width/2,height/2]); // 设置平移量
    		
    		//定义地理路径生成器,使每一个坐标都会先调用此投影,才产生路径值
    		var path=d3.geo.path()
    		.projection(projection);// 设定投影
    		
    		//3.请求china.geo.json数据,添加<path>,每个path用于绘制一个省的路径
    		
    		
    		//请求china.geo.json
    		d3.json("china.geo.json",function(err,root){
    			if(err){
    				alert('数据请求失败');
    			}
    			console.log(root);
    			//创建svg
    			
    			
    			var svg = d3.select("body")
    			        .append("svg")
    			        .attr("width", width)
    			        .attr("height", height);
    					
    			var groups=svg.append("g");
    			
    			groups.selectAll("path")
    			.data(root.features) // 绑定数据
    			.enter()
    			.append("path")
    			.style("fill",'#404466')
    			.attr("d",path);//使用路径生成器
    		})
    		
    		
    	</script>
    </html>
    
    

    访问本地json文件产生跨域问题

    在浏览器打开页面时,可能会有跨域问题,网上有很多解决方法,主要是使json文件和页面在同一个域内。我使用的是phpstudy来解决这个问题。
    效果:

    移入某省显示其他颜色

    加入两个事件:mouseover和mouseout

    groups.selectAll("path")
    			.data(root.features) // 绑定数据
    			.enter()
    			.append("path")
    			.on('mouseover',function(d,i){
    				
    				d3.select(this)
    				.style('fill','#2CD8FF')
    				
    			})
    			.on('mouseout',function(d,i){
    				d3.select(this)
    				.style('fill', '#404466')
    			})
    			.style("fill",'#404466')//填充内部颜色
    			.attr("d",path)//使用路径生成器
    

    还可以在这两个事件中改变边框颜色

    做鼠标文字跟随

    想要有文字可以跟随鼠标移动,需要获取鼠标位置。为了方便使用,我们选用offsetX,offsetY,获取方法mouseXY()。
    然后根据这两个位置绘制一个方框,里面填入相应的省份方法createFangkuang()。
    还需要有三个事件:

    • mouseover:鼠标移入,创建跟随方框
    • mousemove:鼠标移动,删除上一个方框,根据新的鼠标位置创建新方框。
    • mouseout:鼠标移除,删除方框

    代码:

    .fangkuang{
    			 100px;
    			height: 100px;
    			padding: 5px;
    			
    			opacity: 0.6;
    			border:1px solid #fff;
    			border-radius: 5px;
    			
    		}
    		
    		.......
    		
            //返回当前鼠标位置
    		function mouseXY(e){
    			var e=e||window.event;
    			return { "x": e.offsetX, "y": e.offsetY };
    		}
    		
    		//移除方框
    		function fangkuangRemove()
    		{
    			d3.select("#fangkuang1").remove();
    			d3.select("#fangkuang2").remove();
    		}
    		//创建方框和文字
    		function createFangkuang(svg,d)
    		{
    			
    			let XY=mouseXY(event);
    			svg.append("rect")
    			        .attr("id", "fangkuang1")
    			        .attr("x", XY.x)
    			        .attr("y",XY.y)
    					.attr("class","fangkuang")
    		//创建显示tooltip文本
    		svg.append("text")
    			        .attr("id", "fangkuang2")
    			        .attr("x", XY.x+40)
    			        .attr("y",XY.y+20)
    			        .attr("text-anchor", "middle")
    			        .attr("font-family", "sans-serif")
    			        .attr("font-size", "14px")
    			        .attr("font-weight", "bold")
    			        .attr("fill", "#fff")
    			        .text(d.properties.name);
    		}
    	......
    	
    	groups.selectAll("path")
    			.data(root.features) // 绑定数据
    			.enter()
    			.append("path")
    			.on('mouseover',function(d,i){
    				d3.select(this)
    				.style('fill','#2CD8FF');
    				console.log('ss');
    				createFangkuang(svg,d);				
    			})
    			.on('mousemove',function(d,i){
    				fangkuangRemove();
    				createFangkuang(svg,d);
    			})
    			.on('mouseout',function(d,i){
    				d3.select(this)
    				.style('fill', '#404466');
    				fangkuangRemove();
    			})
    			.style("fill",'#404466')//填充内部颜色
    			.attr("d",path)//使用路径生成器
    

    效果:

    产生方框不停闪动的问题及解决办法

    在查看效果时那个跟随方框不停闪动,效果很不好。根据观察和测试,发现它不断的触发mouseover事件,然而按照逻辑应该是将鼠标放在一个新的省份时才会触发它。

    思考了一下事件冒泡的可能性:

    1. 可是这里没有出现父子级都有相同事件的情况,所以这种情况排除。
    2. 又想会不会是在移动的过程中鼠标指向的元素可能不是,而变成了它的父节点svg或是移动到了rect,text内,导致鼠标暂时离开path,造成不断触发了mouseover,mouseout事件。经过检查,发现确实是这样,在向方框的方向移到是,鼠标移到了rect,text内,造成闪动。

    解决方法:

    • 将offsetX改为clientX,这样不会产生闪动的问题,但是clientX是鼠标到浏览器窗口的左上角,要想鼠标跟随,需要计算,这样不方便。
    • 将方框放到离鼠标有一段距离的地方,保持距离,让鼠标在移动时不会移动到方框内。
    • 有一个css样式:pointer-events:none;元素不再是鼠标事件的目标,鼠标不再监听当前层而去监听下面的层中的元素。

    看情况可作出适当选择。

    代码

    <!DOCTYPE html>
    <html>
    	<head>
    		<meta charset="utf-8">
    		<title>中国地图</title>
    		<script src="http://d3js.org/d3.v3.min.js"></script>
    	</head>
    	<style>
    		.fangkuang{
    			 100px;
    			height: 100px;
    			padding: 5px;
    			
    			opacity: 0.6;
    			border:1px solid #fff;
    			border-radius: 5px;
    			
    		}
    		#fangkuang1{
    			pointer-events: none;
    		}
    		#fangkuang2{
    			pointer-events: none;
    		}
    		
    	</style>
    	<body>
    		<svg></svg>
    	</body>
    	<script>
    		
    		var width = 960, height = 700;
    		//1.定义投影和生成器
    		//定义地图投影
    		var projection=d3.geo.mercator()
    		.center([107,31]) //地图中心位置,107是经度,31是纬度
    		.scale(600) //设置缩放量
    		.translate([width/2,height/2]); // 设置平移量
    		
    		//定义地理路径生成器,使每一个坐标都会先调用此投影,才产生路径值
    		var path=d3.geo.path()
    		.projection(projection);// 设定投影
    		
    		//3.请求china.geo.json数据,添加<path>,每个path用于绘制一个省的路径
    		/**
    		 * 获取鼠标位置
    		 * @param {Object} e 当前的元素对象
    		 */
    		function mouseXY(e){
    			var e=e||window.event;
    			return { "x": e.offsetX, "y": e.offsetY };
    		}
    		
    		/**
    		 * 删除文字和方框
    		 */
    		function fangkuangRemove()
    		{
    			d3.select("#fangkuang1").remove();
    			d3.select("#fangkuang2").remove();
    		}
    		/**
    		 * 创建方框和框内文字
    		 * @param {Object} svg 
    		 * @param {Object} d
    		 */
    		function createFangkuang(svg,d)
    		{
    			
    			let XY=mouseXY(event);
    			svg.append("rect")
    			        .attr("id", "fangkuang1")
    			        .attr("x", XY.x)
    			        .attr("y",XY.y)
    					.attr("class","fangkuang")
    			//创建显示tooltip文本
    			svg.append("text")
    			        .attr("id", "fangkuang2")
    			        .attr("x", XY.x+40)
    			        .attr("y",XY.y+20)
    			        .attr("text-anchor", "middle")
    			        .attr("font-family", "sans-serif")
    			        .attr("font-size", "14px")
    			        .attr("font-weight", "bold")
    			        .attr("fill", "#fff")
    			        .text(d.properties.name);
    		}
    		//请求china.geo.json
    		d3.json("http://localhost/china.geo.json",function(err,root){
    			if(err){
    				alert('数据请求失败');
    			}
    			console.log(root);
    			//创建svg
    			var svg = d3.select("body")
    			        .append("svg")
    			        .attr("width", width)
    			        .attr("height", height);
    					
    			var groups=svg.append("g");
    			
    			groups.selectAll("path")
    			.data(root.features) // 绑定数据
    			.enter()
    			.append("path")
    			.on('mouseover',function(d,i){
    				d3.select(this)
    				.style('fill','#2CD8FF');
    				console.log('ss');
    				createFangkuang(svg,d);				
    			})
    			.on('mousemove',function(d,i){
    				fangkuangRemove();
    				createFangkuang(svg,d);
    			})
    			.on('mouseout',function(d,i){
    				d3.select(this)
    				.style('fill', '#404466');
    				fangkuangRemove();
    			})
    			.style("fill",'#404466')//填充内部颜色
    			.attr("d",path)//使用路径生成器
    			
    		})
    	</script>
    </html>
    
    

    附录

    chain.geo.json:
    https://github.com/ELLENXX/d3-GeoJSON-.git

  • 相关阅读:
    redis数据结构详解之Hash(四)
    Redis数据结构详解之Set(三)
    Redis数据结构详解之List(二)
    Redis数据结构详解(一)
    memcached安装及.NET中的Memcached.ClientLibrary使用详解
    Quartz.net开源作业调度框架使用详解
    quartz.net 时间表达式----- Cron表达式详解
    MongoDB高级查询详细
    MongoDB下载安装与简单增删改查
    MSSQLSERVER添加c# clr程序集的使用方法
  • 原文地址:https://www.cnblogs.com/ellen-mylife/p/12022299.html
Copyright © 2011-2022 走看看