It's only code. But inside, there's passion.

Geo Distance

Source

<?php

/**
 * Fetches the distance between two given german country codes.
 * 
 * This function will need a MySQL database with the OpenGeoDB data.
 * You can get this under: http://opengeodb.hoppe-media.com/
 *
 * @author      Denis Perrevoort <denis@perrevoort.com>
 * @version     1.0.0
 * @link        http://perrevoort.com/en/repository/GeoDistance
 * @param       string      $plz_1
 * @param       string      $plz_2
 * @return      float       $distance
 */

function fetchDistanceByPLZ($plz_1$plz_2)
{
  
$database 'geodb';
  
  if(
strlen($plz_1) != || strlen($plz_2) != || !is_numeric($plz_1) || !is_numeric($plz_2))
    return -
1;  // At least one of both codes is invalid
  
elseif($plz_1 == $plz_2)
    return 
0;   // Same country codes - distance is null
    
  // Statement to query the Distance from the OpenGeoDB database
  // 1.85201 is the conversion factor from nautical miles to kilometers
  
$sql "
    SELECT
      DEGREES(
        ACOS(
            SIN(RADIANS(c1.lat)) * SIN(RADIANS(c2.lat))
          + COS(RADIANS(c1.lat)) * COS(RADIANS(c2.lat))
          * COS(RADIANS(c1.lon - c2.lon))
        ) * 60 * 1.85201
      ) AS distance
    FROM
      {$database}.geodb_textdata    t1,
      {$database}.geodb_textdata    t2,
      {$database}.geodb_coordinates c1,
      {$database}.geodb_coordinates c2
    WHERE
          t1.text_type = 500300000
      AND t2.text_type = 500300000
      AND t1.text_val  = \"{$plz_1}\"
      AND t2.text_val  = \"{$plz_2}\"
      AND c1.loc_id    = t1.loc_id
      AND c2.loc_id    = t2.loc_id
    "
;
  
  
$query mysql_query($sql);
  if(
$row mysql_fetch_assoc($query))
  {
    
// get the database result and round it
    
if($row['distance'] < 100)
      
// return distance (in km) round to one position after decimal point
      
return round($row['distance'], 1);
    else
      
// round to no position after decimal point from 100km and more
      
return round($row['distance'], 0);
  }
  else
  {
    
// No result found
    
return -1;
  }
}

?>

Example

<?

require_once('function.fetchDistancebyPLZ.php');

$plz_1 $_GET['plz_1'];  // e.g. '60311' (Country code for Frankfurt)
$plz_2 $_GET['plz_2'];  // e.g. '95444' (Country code for Bayreuth)

$distance fetchDistanceByPLZ($plz_1$plz_2);

echo(
"Distance: {$distance} km");

?>

Output

Distance: 207.6 km

 

License: All code on this website resides in the Public Domain, you are free to use and modify it however you wish.

Note: If you do use code from this site, please leave the original author information attached.