Under Reconstruction

Calculating GPS Distance in PHP

Posted on 20 May 2017

During the initial design and implementation phases of ForenCity, I have to test out whether the player is actually inside a scene. This current implementation only allows us to configure a GPS point for a scene and test whether the player is inside a specified radius.

Doing so was quite easy in two steps:

  • Calculate the distance between the player and the defined GPS point
  • Determine whether this distance is smaller or larger than the defined radius

The distance is calculated as follows:

function distance($latitude1, $longitude1, $latitude2, $longitude2) {
    // Convert Degrees to Radians
    $latitude1 = deg2rad($latitude1);
    $longitude1 = deg2rad($longitude1);
    $latitude2 = deg2rad($latitude2);
    $longitude2 = deg2rad($longitude2);

    // Earth's radius in metres
    $EarthRadius = 6371000; 

    // Some "basic" Trigonometry
    return acos(sin($latitude1)*sin($latitude2) + 
                cos($latitude1)*cos($latitude2) * 
           * $EarthRadius;

So, let’s say our point is the Great Sphinx in Egypt:

// 29°58'18.59" N 31°08'09.60" E
$pointLatitude = 29.971829446;
$pointLongitude = 31.135999456;

and our user is here:

// 29°58'18.62" N 31°08'09.24" E
$userLatitude = 29.971839576;
$userLongitude = 31.135899326;

the distance between the two points is 9.71m

Now, we can write a basic function to test whether two points is within a predefined function.

function test_gps($userLatitude, $userLongitude, $pointLatitude, $pointLongitude, $radius) {
    if (distance($userLatitude, $userLongitude, $pointLatitude, $pointLongitude) <= $radius){
        return true;
    return false;

and if we then run

test_gps($userLatitude, $userLongitude, $pointLatitude, $pointLongitude, 10);
// Result is TRUE

Later implementations of ForenCity will allow us to define areas using a polygon. I bet that will be easy to solve…