电子围栏:根据经纬度判断一点是否在不规则多边形区域内


一、不规则多边形:奇内偶外

  /**

  *$lon 经度 string

  *$lat 维度 string

  *$coords 不规则多边形的点 json字符串

  */

function isPointInPolygon( $lon, $lat, $coords ){
  $wn = 0;
  $shift = false;
  if( $coords[0]['lat'] > $lat ) {
    $shift = true;
  }

  for( $i = 1; $i<count( $coords ); $i++ ){
    $shiftp = $shift;
    $shift = $coords[$i]['lat'] > $lat;

    if( $shiftp != $shift ) {
      $n = ( $shiftp ? 1 : 0 ) - ( $shift ? 1 : 0 );
      if( $n * (( $coords[$i-1]['lng'] - $lon ) * ( $coords[$i]['lat'] - $lat ) - ( $coords[$i-1]['lat'] - $lat ) * ( $coords[$i]['lng'] - $lon ) )> 0) {
        $wn += $n;
      }
    }
  }
  echo $wn;
}

例:

$coords='[{lng:116.398718, lat:39.921917}, {lng:116.394334, lat:39.911735}, {lng:116.564202, lat:39.757502}, {lng:116.603296, lat:39.959553}, {lng:116.419415, lat:39.915055}, {lng:116.415319, lat:39.921585}, {lng:116.407126, lat:39.923245}, {lng:116.37218, lat:39.948934},{lng:116.398718, lat:39.921917}]';
$coords = str_replace("l", "\"l", str_replace("g", "g\"", str_replace("t", "t\"", $coords)));
$coords = json_decode( $coords, true );
//里边
$lon = 116.434164;
$lat = 39.909622;

isPointInPolygon($lon, $lat, $coords);

二、圆形区域

/**

  *$lon1 经度1 string

  *$lat1 维度1 string

  *$lon2 圆心经度1 string

  *$lat2 圆心维度1 string

  *$radius 半径

  */

function circle($lat1,$lng1,$lat2,$lng2,$radius){
  $EARTH_RADIUS = 6378.137;
  $radLat1 = $this->rad($lat1);
  $radLat2 = $this->rad($lat2);
  $a = $radLat1 - $radLat2;
  $b = $this->rad($lng1) - $this->rad($lng2);
  $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
  $s = $s * $EARTH_RADIUS;
  $s = round($s * 1000) / 1000;
  return $s>$radius ? 0 : 1;
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM