之前碰到的這樣一個需求,要將公司的服務在地圖中顯示出來,並將用戶每天的訪問坐標進行統計看有多少用戶是在所能達到的服務范圍半徑內。
以下是PHP代碼的實現 (僅驗證坐標在某片坐標區域內)
<?php /** * 驗證坐標點是否在某區域內 * @author xiaoliang <[email protected]> * Class validationMap */ class validationMap{ private static $coordArray; private static $vertx = []; private static $verty = []; /** * 設置坐標區域 * @param mixed $coordArray */ public static function setCoordArray(array $coordArray) { self::$coordArray = $coordArray; } /** * 驗證區域范圍 * @param array $coordArray * @return bool */ public static function isCityCenter(array $coordArray){ if(!self::vaildatePoint($coordArray)){ return false; } return self::pnpoly(count(self::$coordArray), $coordArray['lng'], $coordArray['lat']); } /** * 比較區域坐標 * @param $nvert * @param $testx * @param $testy * @return bool */ private static function pnpoly($nvert,$testx, $testy) { $c = false; for ($i = 0, $j = $nvert-1; $i < $nvert; $j = $i++) { if ( ( (self::$verty[$i]>$testy) != (self::$verty[$j]>$testy) ) && ($testx < (self::$vertx[$j]-self::$vertx[$i]) * ($testy-self::$verty[$i]) / (self::$verty[$j]-self::$verty[$i]) + self::$vertx[$i]) ) $c = !$c; } return $c; } /** * 驗證坐標 * @param array $pointArray * @return bool */ private static function vaildatePoint(array $pointArray){ $maxY = $maxX = 0; $minY = $minX = 9999; foreach (self::$coordArray as $item){ if($item['lng']>$maxX) $maxX = $item['lng']; if($item['lng'] < $minX) $minX = $item['lng']; if($item['lat']>$maxY) $maxY = $item['lat']; if($item['lat'] < $minY) $minY = $item['lat']; self::$vertx[] = $item['lng']; self::$verty[] = $item['lat']; } if ($pointArray['lng'] < $minX || $pointArray['lng'] > $maxX || $pointArray['lat'] < $minY || $pointArray['lat'] > $maxY) { return false; } return true; } }
/**************************** test *************************************/ $map = [ //上海 ["lng" => 121.488286, "lat" => 31.420147], ["lng" => 121.702154, "lat" => 31.294828], ["lng" => 121.780918, "lat" => 31.141157], ["lng" => 121.782068, "lat" => 30.941157], ["lng" => 121.492885, "lat" => 30.909931], ["lng" => 121.22325, "lat" => 30.890099], ["lng" => 121.161482, "lat" => 31.015526], ["lng" => 121.076395, "lat" => 31.226239], ["lng" => 121.189873, "lat" => 31.339688], ["lng" => 121.459509, "lat" => 31.41368], ]; $array = ["lat"=>31.218681,"lng"=>121.08604];//進行驗證的區域 validationMap::setCoordArray($map); var_dump(validationMap::isCityCenter($array));
在地圖中的運用: