0

So i'm trying to get the distance between to coordinates using php. I'm using these two functions:

  1. locate user by ip
  2. get image with gps coordinates

in locate user by ip i'm getting the latitude and longitude from the ip, and the putting them in $ lat1 and $ lon1

$ip = $_SERVER['REMOTE_ADDR'];
$details = json_decode(file_get_contents("http://ipinfo.io/{$ip}/json"));
$user_location = $details->loc;
$pieces = explode(",", $user_location);
$lat1 = $pieces[0];
$lon1 = $pieces[1];
$unit = "Km";

in get image i'm selecting the rows, and they all contain the latitude and longitude from the exif.

function get_image($db){
    $select = "id, image_name";
    $sql = "SELECT $select FROM images ORDER BY id DESC";
    $stmt = $db->prepare($sql);
    $stmt->execute();
    $spot = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if(!$stmt -> rowCount()){
        echo "<div class='noSpots'>
                    <p>Sorry there seams to be nothing in your area</p>
              </div>";
    }
        return $spot;
}//spots_narrow ends here

so after these two functions I can now return four variables with the two latitudes and longitudes that i want to calculate the distance between.

- $ lat1
- $ lon1
- $ lat2
- $ lon2
user3426191
  • 71
  • 1
  • 10

2 Answers2

1

You want to look at the Haversine Formula I'm not keen on PHP, but in pseudo php code this is how it goes:

$EarthRadius = 6371000; // radius in meters
$phi1 = deg2rad($lat1)
$phi2 = deg2rad($lat2)
$deltaLat = deg2rad($lat2 - $lat1)
$deltaLon = deg2rad($lon2 - $lon1)

var $a = sin($deltaLat/2) * sin($deltaLat/2) + cos($phi1) * cos($phi2) * sin($deltaLon / 2) * sin($deltaLon / 2);
var $c = 2 * atan2(sqrt($a), sqrt(1 - $a));

var $result = $EarthRadius * $c;

You should be able to find equivalent formulas for cos, sin, atan2 in PHP Math modules. There are also some other approximations but this should work quite fine.

Jonathan Nazario
  • 133
  • 3
  • 13
0

From http://rosettacode.org/wiki/Haversine_formula#PHP

class POI {
    private $latitude;
    private $longitude;
    public function __construct($latitude, $longitude) {
        $this->latitude = deg2rad($latitude);
        $this->longitude = deg2rad($longitude);
    }
    public function getLatitude() return $this->latitude;
    public function getLongitude() return $this->longitude;
    public function getDistanceInMetersTo(POI $other) {
        $radiusOfEarth = 6371000;// Earth's radius in meters.
        $diffLatitude = $other->getLatitude() - $this->latitude;
        $diffLongitude = $other->getLongitude() - $this->longitude;
        $a = sin($diffLatitude / 2) * sin($diffLatitude / 2) +
            cos($this->latitude) * cos($other->getLatitude()) *
            sin($diffLongitude / 2) * sin($diffLongitude / 2);
        $c = 2 * asin(sqrt($a));
        $distance = $radiusOfEarth * $c;
        return $distance;
    }
}
Chad Kennedy
  • 1,716
  • 13
  • 16