点与不规则图形关系判断

 1 <html>  
 2 <head>  
 3 <meta http-equiv="Content-Type" content="text/html; charset=gbk">  
 4 <title>img usemap属性</title>  
 5 </head>
 6 <script>
 7 
 8 function isPointInLine(point,linePoint1,linePoint2)
 9 {
10     //是否一个点向x轴的射线穿透线段,有交点
11     var maxY=(linePoint1.y>linePoint2.y)?linePoint1.y:linePoint2.y;
12     var minY=(linePoint1.y<linePoint2.y)?linePoint1.y:linePoint2.y;
13     //alert("maxY" + maxY);
14     //alert("minY = " + minY);
15     var re=false;
16     if(point.y<maxY && point.y>=minY)
17     {
18         a1 = point.x;
19         a2 = (linePoint2.x-linePoint1.x)*(point.y-linePoint1.y)/(linePoint2.y-linePoint1.y);
20         //alert(a1);
21         //alert(a2);
22         //alert(a1 <= a2);
23         if(parseFloat(point.x) <= parseFloat(( linePoint1.x+(linePoint2.x-linePoint1.x)*(point.y-linePoint1.y)/(linePoint2.y-linePoint1.y) )) )
24         {
25         re=true;
26         }
27     }
28     //alert("point :" + point.x + ":" + point.y + ";")
29     //alert("linePoint1 :" + linePoint1.x + ":" + linePoint1.y + ";")
30     //alert("linePoint2 :" + linePoint2.x + ":" + linePoint2.y + ";")
31     //alert(re);
32     return(re);
33 }
34 
35 function isPointInPolygon(point,poly)
36 {
37     //是否点在多边形里 
38     var crossNum=0;
39     var re=true;
40     for(var i=0;i<poly.length-1;i++)
41     {
42         if(isPointInLine(point,poly[i],poly[i+1]))
43         {
44             crossNum++;
45         }
46     }
47     
48     if((crossNum % 2)==0)
49     {
50         re=false;
51     }
52     
53     return(re);
54 }
55 
56 function clickme()
57 {
58     var pa = document.getElementById("point").value.split(",");
59     var p = {x:pa[0],y:pa[1]};
60     
61     var poa = document.getElementById("poly").value.split(",");
62     var po = new Array();
63     for(var i=0;i<poa.length/2;i++){
64         po[i]={x:poa[2*i],y:poa[2*i+1]};
65     };
66     //for(var i=0;i<po.length;i++)
67     //{
68     //    alert(po[i].x);
69     //    alert(po[i].y);
70     //}
71 
72     //alert(p.x);
73     //alert(p.y);
74 
75     alert(isPointInPolygon(p,po));
76 }
77 </script>
78   
79 <body>
80     原理:从要判断的点向x轴发射一条射线,如果射线与多边形的边有偶数次相交,那么点不在多边形内;奇数次相交,那么点在多边形内(<font color="red">*此处的坐标是平面坐标</font>)
81     <br>
82 <input type="text" id="point" value="0.5,0.49" />点的横竖坐标,用逗号分隔
83 <br>
84 <input type="text" id="poly" value="0,0,0.75,0.75,1,0,1,1,0,1" />按照逆时针方向 多边形点的横竖坐标坐标0
85 <input type="button" id="btn" value="点击我" onclick="clickme();">
86 </body>
87 </html>

原理:

 从要判断的点向x轴发射一条射线,如果射线与多边形的边有偶数次相交,那么点不在多边形内;奇数次相交,那么点在多边形内
posted @ 2014-09-01 11:38  GisClub  阅读(824)  评论(0编辑  收藏  举报