Created
January 5, 2016 13:13
-
-
Save theraaz/7da209ae45b5e14fa6d5 to your computer and use it in GitHub Desktop.
calculate distance between two points in 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 | |
| /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ | |
| /* based on : https://github.com/chrisveness/geodesy */ | |
| /* */ | |
| /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ | |
| /** | |
| * Class LatLon | |
| * Creates a LatLon point on the earth's surface at the specified latitude / longitude. | |
| */ | |
| class LatLon | |
| { | |
| public $lat; | |
| public $lon; | |
| private $radius = 6371e3; // (Mean) radius of earth (defaults to radius in metres). | |
| function __construct($lat, $lon) | |
| { | |
| $this->lat = $lat; | |
| $this->lon = $lon; | |
| } | |
| /** | |
| * Returns the distance from 'this' point to destination point (using haversine formula). | |
| * @param {LatLon} $point - Latitude/longitude of destination point. | |
| * @return float Distance between this point and destination point, in same units as radius.(meters) | |
| */ | |
| function distanceTo($point){ | |
| if (!is_a($point, 'LatLon') || !is_a($point, 'LatLon')) | |
| return 0; | |
| //convert to radians | |
| $from = $this->toRadians(); | |
| $to = $this->toRadians($point); | |
| $latDiff = $to->lat - $from->lat; | |
| $lonDiff = $to->lon - $from->lon; | |
| $a = sin($latDiff / 2) * sin($latDiff / 2) + | |
| cos($from->lat) * cos($to->lat) * | |
| sin($lonDiff / 2) * sin($lonDiff / 2); | |
| $c = 2 * atan2(sqrt($a), sqrt(1 - $a)); | |
| return $d = $this->radius * $c; // in meters | |
| } | |
| private function toRadians($point = null){ | |
| $point = $point ? $point : $this; | |
| $point->lat *= M_PI / 180; | |
| $point->lon *= M_PI / 180; | |
| return $point; | |
| } | |
| public static function metersToMiles($i) { | |
| return $i*0.000621371192; | |
| } | |
| public static function milesToMeters($i) { | |
| return $i*1609.344; | |
| } | |
| } | |
| $from = new LatLon(48.857, 2.351); | |
| echo LatLon::metersToMiles($from->distanceTo(new LatLon(52.205, 0.119))); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment