Online Shopping : Computers : Programming : Languages : PHP

+ Search
Add Entry AlertManage Folder Edit Entry Add page to
Did You Find This Entry Useful?

89 of 170 people (52%) answered Yes
Recently 3 of 10 people (30%) answered Yes


How to calculate the distance between two locations on the earth?
How to calculate distances based on latitude and longitude?
How to implement a "store locator" based on a user's ZIP code, which lists the closest dealers from our database?

Mar 15th, 2008 18:04
ha mo, Articles Hosting, Shashank Tripathi,

Although some commercial products exist to do this, e.g., Zipfind's 
Locator (, the basic idea behind 
this is to calculate the distance between latitude and longitude of 
different locations. For some good references and some sample code, 
please visit this website: 
But for the purposes of this question itself, the following code 
should be useful: 
// Function takes latitude and longitude  of two places as input
// and retuns a string with the distance in miles and KMs. 
function converLatitudeLongitudeToMiles($lat1, $lon1, $lat2, $lon2)
    // This is the formula for calculating distances
    // from latitude and longitude.
    $dist   = acos(sin(deg2rad($lat1))
              * sin(deg2rad($lat2)) + cos(deg2rad($lat1))
              * cos(deg2rad($lat2))
              * cos(deg2rad($lon1 - $lon2)));
    $dist   = rad2deg($dist);
    $miles  = (float) $dist * 69;
    // To get kilometers, multiply miles by 1.61
    $km     = (float) $miles * 1.61;
    // This is all displaying functionality
    $display  = sprintf("%0.2f",$miles) . " miles" ;
    $display .= " (" . sprintf("%0.2f",$km) . " kilometers)" ;
    return $display ;
i hope that helps.