mysql空間查詢並不太適合地圖座標,若是使用:http://www.cnblogs.com/tyjsjl/p/8760002.html的方式進行地圖點座標的查詢就很差用了,因而直接使用php來進行地圖範圍的查詢更方便點。代碼以下:php
1 /** 2 * 驗證座標點是否在某區域內 3 * @author xiaoliang <1058436713@qq.com> 4 * Class validationMap 5 */ 6 class validationMap{ 7 private $coordArray; 8 private $vertx = []; 9 private $verty = []; 10 /** 11 * 設置座標區域 12 * @param mixed $coordArray 13 */ 14 public function setCoordArray(array $coordArray) 15 { 16 $this->coordArray = $coordArray; 17 } 18 /** 19 * 驗證區域範圍 20 * @param array $coordArray 21 * @return bool 22 */ 23 public function isCityCenter(array $coordArray){ 24 if(!$this->vaildatePoint($coordArray)){ 25 return false; 26 } 27 return $this->pnpoly(count($this->coordArray), $coordArray['lng'], $coordArray['lat']); 28 } 29 /** 30 * 比較區域座標 31 * @param $nvert 32 * @param $testx 33 * @param $testy 34 * @return bool 35 */ 36 private function pnpoly($nvert,$testx, $testy) 37 { 38 $c = false; 39 for ($i = 0, $j = $nvert-1; $i < $nvert; $j = $i++) { 40 if ( ( ($this->verty[$i]>$testy) != ($this->verty[$j]>$testy) ) && ($testx < ($this->vertx[$j]-$this->vertx[$i]) * ($testy-$this->verty[$i]) / ($this->verty[$j]-$this->verty[$i]) + $this->vertx[$i]) ) 41 $c = !$c; 42 } 43 return $c; 44 } 45 /** 46 * 驗證座標 47 * @param array $pointArray 48 * @return bool 49 */ 50 private function vaildatePoint(array $pointArray){ 51 $maxY = $maxX = 0; 52 $minY = $minX = 9999; 53 foreach ($this->coordArray as $item){ 54 if($item['lng']>$maxX) $maxX = $item['lng']; 55 if($item['lng'] < $minX) $minX = $item['lng']; 56 if($item['lat']>$maxY) $maxY = $item['lat']; 57 if($item['lat'] < $minY) $minY = $item['lat']; 58 $this->vertx[] = $item['lng']; 59 $this->verty[] = $item['lat']; 60 } 61 if ($pointArray['lng'] < $minX || $pointArray['lng'] > $maxX || $pointArray['lat'] < $minY || $pointArray['lat'] > $maxY) { 62 return false; 63 } 64 return true; 65 } 66 }
/**************************** 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));
由於每一個區域的地圖點座標須要從數據庫提取進行查詢,因此靜態類就不太方便了,本文代碼不使用靜態類。關於靜態類的優缺點在此不做說明。html
原文代碼:https://www.cnblogs.com/liang94/p/5936583.htmlmysql