Con
esta función:
Código PHP:
function calcularDistancia($latitud1, $longitud1, $latitud2, $longitud2, $unidad = 'km')
{
$latitud1 = deg2rad($latitud1);
$longitud1 = deg2rad($longitud1);
$latitud2 = deg2rad($latitud2);
$longitud2 = deg2rad($longitud2);
$p = sin($latitud1) * sin($latitud2) + cos($latitud1) * cos($latitud2) * cos($longitud1 - $longitud2);
$d = rad2deg(acos($p));
switch ($unidad)
{
case 'milla':
$x = 69.09;
break;
case 'km':
default:
$x = 111.194;
}
$total = $d * $x;
return round($total);
}
$ciudades = array(
'Madrid' => array(40.563895, -3.702393),
'Paris' => array(48.886843, 2.351074),
'Nueva York' => array(40.853293, -74.006653)
);
if (
isset($_GET['desde']) && isset($ciudades[$_GET['desde']]) &&
isset($_GET['hasta']) && isset($ciudades[$_GET['hasta']])
)
{
$distancia = calcularDistancia(
$ciudades[$_GET['desde']][0], $ciudades[$_GET['desde']][1],
$ciudades[$_GET['hasta']][0], $ciudades[$_GET['hasta']][1]
);
echo 'Hay '.$distancia.' km';
}
else
{
$select = '<select name="%NAME%">';
foreach ($ciudades as $ciudad => $datos)
{
$select .= '<option value="'.$ciudad.'">'.$ciudad.'</option>';
}
$select .= '</select>';
echo '
<form>
De '.str_replace('%NAME%', 'desde', $select).'
<br />
A '.str_replace('%NAME%', 'hasta', $select).'
<br />
<input type="submit" value="Calcular">
</form>
';
}