經緯度多邊形點判斷
阿新 • • 發佈:2019-02-16
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8">
<head>
</head>
</head>
<body style="background:#f8f9fa;">
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
var p = [116.428752 , 40.065088];//測試gps座標
var lp = {
p0:[116.361774 , 39.949914],
p1:[116.423578 , 40.064204],
p2:[116.252253 , 40.178962],
p3:[116.540286 , 40.045206],
p4:[116.44025 , 39.910299],
p5:[116.44025 , 39.952791]
}//gps座標劃的圍欄
var nCount = 6;//lp的個數
function PtInPolygon (p , lp, nCount)
{
var nCross = 0;
for (var i = 0; i < nCount; i++)
{
console.log('a'+i);
var pt1 = lp['p'+i];
var pt2 = lp['p'+(i+1)%nCount];
// 求解 y=p.y 與 p1p2 的交點
if ( pt1[1]== pt2[1] ) // p1p2 與 y=p0.y平行
continue;
if ( p[1] < pt1[1] && p[1] < pt2[1] ) // 交點在p1p2延長線上
continue;
if ( p[1] >= pt1[1] && p[1] >= pt2[1] ) // 交點在p1p2延長線上
continue;
// 求交點的 X 座標 --------------------------------------------------------------
var x = (p[1] - pt1[1]) * (pt2[0] - pt1[0]) / (pt2[1] - pt1[1]) + pt1[0];
if ( x > p[0] )
nCross++; // 只統計單邊交點
console.log('b'+nCross);
}
// 單邊交點為偶數,點在多邊形之外 ---
return (nCross % 2 == 1);
}
alert(PtInPolygon (p , lp, nCount));
</script>
</body>
</html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8">
<head>
</head>
</head>
<body style="background:#f8f9fa;">
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
var p = [116.428752 , 40.065088];//測試gps座標
var lp = {
p0:[116.361774 , 39.949914],
p1:[116.423578 , 40.064204],
p2:[116.252253 , 40.178962],
p3:[116.540286 , 40.045206],
p4:[116.44025 , 39.910299],
p5:[116.44025 , 39.952791]
}//gps座標劃的圍欄
var nCount = 6;//lp的個數
function PtInPolygon (p , lp, nCount)
{
var nCross = 0;
for (var i = 0; i < nCount; i++)
{
console.log('a'+i);
var pt1 = lp['p'+i];
var pt2 = lp['p'+(i+1)%nCount];
// 求解 y=p.y 與 p1p2 的交點
if ( pt1[1]== pt2[1] ) // p1p2 與 y=p0.y平行
continue;
if ( p[1] < pt1[1] && p[1] < pt2[1] ) // 交點在p1p2延長線上
continue;
if ( p[1] >= pt1[1] && p[1] >= pt2[1] ) // 交點在p1p2延長線上
continue;
// 求交點的 X 座標 --------------------------------------------------------------
var x = (p[1] - pt1[1]) * (pt2[0] - pt1[0]) / (pt2[1] - pt1[1]) + pt1[0];
if ( x > p[0] )
nCross++; // 只統計單邊交點
console.log('b'+nCross);
}
// 單邊交點為偶數,點在多邊形之外 ---
return (nCross % 2 == 1);
}
alert(PtInPolygon (p , lp, nCount));
</script>
</body>
</html>