php - get distance between two coordinates in km -


this question has answer here:

so i'm trying distance between coordinates using php. i'm using these 2 functions:

  1. locate user ip
  2. get image gps coordinates

in locate user ip i'm getting latitude , longitude ip, , putting them in $ lat1 , $ 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 image i'm selecting rows, , contain latitude , longitude exif.

function get_image($db){     $select = "id, image_name";     $sql = "select $select images order 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 nothing in area</p>               </div>";     }         return $spot; }//spots_narrow ends here 

so after these 2 functions can return 4 variables 2 latitudes , longitudes want calculate distance between.

- $ lat1 - $ lon1 - $ lat2 - $ lon2 

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;     } } 

Comments