Ordering websites by distance from Charing Cross Ordering websites by distance from Charing Cross

February 19, 2022

openstreetmap

Today I decided to tackle the issue of ordering the website listings by distance from Central London. The traditional centre of London is Charing Cross, which is at a latitude of 51.509 and a longitude of -0.122, this is my centre point.

So i did a little search online and found this PHP function that calculates the distance from this point, for each entry in the database.

function distance($lat1, $lon1, $lat2, $lon2, $unit)
{
    $theta = $lon1 - $lon2;
    $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
    $dist = acos($dist);
    $dist = rad2deg($dist);
    $miles = $dist * 60 * 1.1515;
    $unit = strtoupper($unit);

    if ($unit == "K") {
        return ($miles * 1.609344);
    } elseif ($unit == "N") {
        return ($miles * 0.8684);
    } else {
        return $miles;
    }
}

To get the distance from Charing Cross, it is simply a call to

  $distanceFrom = distance(51.509, -0.122, $lat, $lon, 'M');

To store it in the database I added a 'float' field into the mysql table like so:

  `distance` float NOT NULL,

And updaed the Laravel Controller to order the result by this field

  ORDER BY distance ASC 

And hey presto, the lists of websites are now sorted by distance from Charing Cross!


If you would like to contact me with this form on londinium.com, ilminster.net or via Twitter @andylondon