Cesium开发应用中判读一点是否在多边形里面算法

最近在Cesium开发应用中用到了判读一点是否在多边形里面,经思考做了下面的算法,经验证基本满意,记录下,也供大家参考。我的应用是将一块区域分成等长宽的小块需要用到一点是否在多边形内。

Cesium开发应用中判读一点是否在多边形里面算法_第1张图片

 

/*
	判读一点是否在多边形里面
	参数Point 为 {lon:121.55,lat:38.5556};
	Coordinates 为[[121.50399320088566,38.85714873136916],[121.5163970971094,38.856973204571354],[121.51856192771218,38.8552471908181],[121.51604604351384,38.851414854911376],[121.50843988072964,38.85018616703687],[121.50554368755118,38.850566475147055],[121.50399320088566,38.85714873136916]]
	计算算法原理:若一点在多边形内,点的沿同纬度向东和向西与多边形边上的两点连线与点的纬线相交次数为奇数,南北同理。
	*/
	function isPointInPolygon(Point,Coordinates){
		var isWnum=0;var isEnum=0;var isNnum=0;	var isSnum=0;
		Coordinates.push(Coordinates[0]);//让多边形封口
		var CoordinatesLen = Coordinates.length;
		var Windex=0;var Eindex=0;var Nindex=0;var Sindex=0;
		Coordinates.forEach((item,index) => {	
			if(index < (CoordinatesLen-1) && index>0){
				 if((Point.lat>=item[1] && Point.lat<=Coordinates[index+1][1])&&Point.lon<=item[0]){
						 isWnum++; 
						 Windex=index+1;
					 }else{
						 Windex=0;
					 }
				 if((Point.lat>=item[1] && Point.lat<=Coordinates[index-1][1])&&Point.lon<=item[0] && Windex !=index){
						 isWnum++; 
						 Windex=0;
					 }
				 
				 if((Point.lat>=item[1] && Point.lat<=Coordinates[index+1][1])&&Point.lon>=item[0]){
						 isEnum++; 
						 Eindex=index+1;
					 }else{
						 Eindex=0;
					 }	
				 if((Point.lat>=item[1] && Point.lat<=Coordinates[index-1][1])&&Point.lon>=item[0] &&Eindex!=index){
						 isEnum++; 
						 Eindex=0;
					 }	
				 if((Point.lon>=item[0] && Point.lon<=Coordinates[index+1][0])&& Point.lat<=item[1]){
						 isSnum++; 
						 Sindex=index+1;
				 }else{
					 Sindex=0;
				 }
				 if((Point.lon>=item[0] && Point.lon<=Coordinates[index-1][0]) && Point.lat<=item[1] && Sindex!=index){
						 isSnum++; 
						 Sindex=0;
				 }
				 if((Point.lon>=item[0] && Point.lon<=Coordinates[index+1][0]) && Point.lat>=item[1]){
						 isNnum++; 
						 Nindex=index+1;
					 }else{
						 Nindex=0;
					 }
				if((Point.lon>=item[0] && Point.lon<=Coordinates[index-1][0]) && Point.lat>=item[1] && Nindex!=index){
						 isNnum++; 
						 Nindex=0;
					 }
			}			
		});		
		if (isWnum%2>0 && isEnum%2>0 && isNnum%2>0 && isSnum%2>0){
			return true;
		}else{
			return false;
		}
		
	}

你可能感兴趣的:(javascript,开发语言,ecmascript)