fastread homefastrread library fastread menu

PHP Tutorial : Get distance between two zip codes using php

Tutorial by:Admin      Date: 2016-04-14 02:11:45

❰ Previous Next ❱

Lets calculate the distance between 2 zip codes. You need to first generate longitude and latitude from zip code and then you can calculate the distance between both longitude & latitude and display it in Kilometers or Miles.

// This function returns Longitude & Latitude from zip code.
function getLnt($zip){
$url = "
$result_string = file_get_contents($url);
$result = json_decode($result_string, true);
return $result3[0];

function getDistance($zip1, $zip2, $unit){
$first_lat = getLnt($zip1);
$next_lat = getLnt($zip2);
$lat1 = $first_lat['lat'];
$lon1 = $first_lat['lng'];
$lat2 = $next_lat['lat'];
$lon2 = $next_lat['lng']; 
$dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +
cos(deg2rad($lat1)) * cos(deg2rad($lat2)) *
$dist = acos($dist);
$dist = rad2deg($dist);
$miles = $dist * 60 * 1.1515;
$unit = strtoupper($unit);

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


HTML Code:

<form method="POST" action="?flag=true">
<table border="0" width="100%" cellspacing="0" cellpadding="0">

<td width="23%" height="34">Enter Zip code1</td>
<td width="28%" height="34">
<input type="text" name="zipCode" size="20" 
value="<?php print $_POST['zipCode']; ?>"></td>
<td height="34">&nbsp;</td>

<td width="23%" height="34">Enter Zip Code2</td>
<td width="28%" height="34">
<input type="text" name="zipCode2" size="20" 
value="<?php print $_POST['zipCode2']; ?>"></td>
<td height="34">&nbsp;</td>
<td width="23%" height="34">Unit</td>
<td width="28%" height="34">
<input type="radio" value="K" name="unit" checked> KM 
<input type="radio" value="N" name="unit"> Miles</td>
<td height="34">&nbsp;</td>
<td width="23%" height="34">&nbsp;</td>
<td width="28%" height="34" style="padding-top: 20px">
<input type="submit" value="Submit" name="B1" class="submit_btn"></td>
<td height="34">&nbsp;</td>

To Display Out put:

$distance = getDistance($_POST['zipCode'],$_POST['zipCode2'],$_POST['$unit']);
echo $distance;


❰ Previous Next ❱

PHP Tutorial

Submit Your Thought, Tutorial, Articls etc.

Submit Your Information India's Number one online promotion website