-
-
Save bantya/9a180c7ee250616bab64b88354db2a18 to your computer and use it in GitHub Desktop.
Region categorizer [PHP]
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| $regions = new Regions('General'); | |
| $regions->add('North', 54.5742270, -1.2349560); | |
| $regions->add('North West', 53.9690089, -2.6276908); | |
| $regions->add('East Anglia', 52.6308859, 1.2973550); | |
| $regions->add('Midlands', 52.6368778, -1.1397592); | |
| $regions->add('Wales', 52.1306607, -3.7837117); | |
| $regions->add('South East', 50.7680350, 0.2904720); | |
| $regions->add('Scotland', 56.4906712, -4.2026458); | |
| $regions->add('South West', 50.7772135, -3.9994610); | |
| $regions->add('Ireland', 53.4129100, -8.2438900); | |
| echo $regions->calculate($_GET['lat'], $_GET['lng']); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| class Regions | |
| { | |
| private $regions = array(); | |
| private $default = false; | |
| public function __construct($default = false) | |
| { | |
| $this->default = $default; | |
| } | |
| /** | |
| * @return void | |
| */ | |
| public function add($name, $lat, $lng) | |
| { | |
| $this->regions[] = array('name' => $name, 'lat' => $lat, 'lng' => $lng); | |
| } | |
| /** | |
| * @return string/false | |
| */ | |
| public function calculate($lat, $lng) | |
| { | |
| if (count($this->regions) > 0) { | |
| $nearest = $this->regions[0]; | |
| foreach ($this->regions as $region) { | |
| $nearDist = $this->dist($nearest['lat'], $nearest['lng'], $lat, $lng); | |
| $currentDist = $this->dist($region['lat'], $region['lng'], $lat, $lng); | |
| if ($currentDist < $nearDist) { | |
| $nearest = $region; | |
| } | |
| } | |
| return $nearest['name']; | |
| } | |
| return false; | |
| } | |
| /** | |
| * @return float | |
| */ | |
| private function dist($x1, $y1, $x2, $y2) | |
| { | |
| $xval = pow($x2 - $x1, 2); | |
| $yval = pow($y2 - $y1, 2); | |
| return sqrt($xval + $yval); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment