Localizar puntos en un radio

Formula para buscar y listar localizaciones cercanas a un punto en un radio de kilómetros o millas utilizando las coordenadas geográficas. Los datos Latitud y Longitud datos deben ser indexados para que la búsqueda sea rápida y eficiente.

Ejemplo práctico

País
Código Postal    04810  28003  28024
Distancia

Fórmula


Calc es la variable donde almacenamos la fórmula
Lat y Lon son las coordenadas del punto inicial de búsqueda
Latitude y Longitude no coloreados son los nombres de campos en la base de datos
6378.137 es el diámetro de la tierra en kilómetros, usar: 3963.191 para millas
Calc = 6378.137 * ACos( Cos( RADIANS(Latitude) ) * Cos( RADIANS( Lat ) ) * Cos( RADIANS( Lon ) - RADIANS(Longitude) ) + Sin( RADIANS(Latitude) ) * Sin( RADIANS( Lat ) ) )

SQL = "SELECT Locality, " & Calc & " As Distance FROM Table WHERE " & Calc & " <= '5' ORDER BY Distance"

Ejemplo código ASP y base de datos MS SQL

<%
ISO  = Request.Form("ISO")
PostalCode = Request.Form("PostalCode")
Distance   = Request.Form("Distance")

If Request.Form("Radius") = "K" Then
   Radius = 6378.137                       'Kilometers

Else
   Radius = 3963.191                       'Miles

End If

 
Set Conn = Server.CreateObject("ADODB.Connection")
Conn.Open Application("ConnectionString")
Set RS   = Server.CreateObject("ADODB.Recordset")

' Search postal codes to get the coordinates of first point
' ---------------------------------------------------------
SQL = "SELECT * FROM [PostalCodes] " & ISO & "' "

SQL = SQL & "AND PostalCode = '" & PostalCode & "';"


Set RS = Conn.Execute(SQL)

Lat = RS("Latitude")
Lon = RS("Longitude")

 

'Build the formula in: calc variable for easy handling in SQL statement

calc = Radius & " * ACos( Cos(RADIANS(Latitude)) * Cos(RADIANS(" & Lat & ")) * Cos(RADIANS(" & Lon & ") - RADIANS(Longitude)) + Sin(RADIANS(Latitude)) * Sin(RADIANS(" & Lat & ")) ) "

SQL = "SELECT TOP 100 "
SQL = SQL & "ISO, "
SQL = SQL & "Postalcode, "
SQL = SQL & "Region1, "
SQL = SQL & "Region2, "
SQL = SQL & "Region3, "
SQL = SQL & "Locality, "
SQL = SQL & "Suburb, "
SQL = SQL & "Latitude, "
SQL = SQL & "Longitude, "
SQL = SQL & calc & " AS Distance "
SQL = SQL & "FROM [PostalCodes] "
SQL = SQL & "WHERE (ISO = '" & ISO & "') "
SQL = SQL & "AND " & calc & " <= " & Distance & " "
SQL = SQL & "ORDER BY Distance ;"

Set RS = Conn.Execute(SQL)

DO While Not RS.EOF

     Response.Write RS("ISO") & "<br>"
     Response.Write RS("PostalCode") & "<br>"
     Response.Write RS("Region1") & "<br>"
     Response.Write RS("Region2") & "<br>"
     Response.Write RS("Region3") & "<br>"
     Response.Write RS("Locality") & "<br>"
     Response.Write RS("Suburb") & "<br>"
     Response.Write FormatNumber(RS("Distance"),1) & "<br>"

RS.MoveNext
Loop
RS.Close
Set RS = nothing

Conn.Close
%>

Ejemplo código PHP y base de datos MySQL

<?php
if(isset($_GET['Search']))
{
$PostalCode = $_GET['PostalCode'];
$Distance   = $_GET['distance'];

$sqlstring = "SELECT * FROM PostalCodes WHERE PostalCode = '".$PostalCode."'";
$result = mysql_query($sqlstring);

$row = mysql_fetch_assoc($result);

$Lng = $row["Longitude"] / 180 * M_PI;
$Lat = $row["Latitude"] / 180 * M_PI;

mysql_free_result($result);

$sqlstring2 = "SELECT DISTINCT PostalCode, Locality, (6367.41 * SQRT(2 * (1-Cos(RADIANS(Latitude)) * Cos(".$Lat.") * (Sin(RADIANS(Longitude))*Sin(".$Lng.") + Cos(RADIANS(Longitude)) * Cos(".$Lng.")) - Sin(RADIANS(Latitude)) * Sin(".$Lat.")))) AS Distance FROM PostalCodes WHERE (6367.41 * SQRT(2 * (1 - Cos(RADIANS(Latitude)) * Cos(".$Lat.") * (Sin(RADIANS(Longitude)) * Sin(".$Lng.") + cos(RADIANS(Longitude)) * Cos(".$Lng.")) - Sin(RADIANS(Latitude)) * Sin(".$Lat."))) <= '".$Distance."') ORDER BY Distance";

$result = mysql_query($sqlstring2) or die('query failed: ' . mysql_error());

$str = "<table width=\"300\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">";
$str .= "<tr>";
$str .= "<th>PostalCode</th>";
$str .= "<th>Distance</th>";
$str .= "</tr>";

while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$str .= "<tr><td>".$row["PostalCode"]."</td><td>".$row["place"]."</td><td>".round($row['Distance'])."km</td></tr>";
}

$str .= "</table>";

mysql_free_result($result);
mysql_close($conn);
echo $str;
}
?>
Complementos
Divisiones administrativas
Países
Nombres de países
Monedas
Lenguajes
Formato códigos postales
Zonas horarias
Formulas, ejemplos
Distancia entre puntos
Localizar puntos en radio