以下 SQL 查询使用球面余弦定律计算坐标与表中坐标之间的距离。
d = acos( sin(φ1).sin(φ2) + cos(φ1).cos(φ2).cos(Δλ) ).R
查询使用SQL 数学函数
"SELECT Id,Lat,Long,(6367 * acos( cos( radians(center_lat) )
* cos( radians( Lat ) ) * cos( radians( Long ) - radians(center_lng) )
+ sin( radians(center_lat) ) * sin( radians( Lat ) ) ) ) AS distance FROM table
HAVING distance < radius ORDER BY distance ASC LIMIT 0 , 20"
对 MS SQL 和 C# 使用准备好的语句。
尝试
private static void SqlCommandPrepareEx(string connectionString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand(null, connection);
// Create and prepare an SQL statement.
command.CommandText =
"SELECT Id, Lat, Long, (6367 * acos( cos( radians(@center_lat) ) * cos( radians( Lat ) ) * cos( radians( Long ) - radians(@center_lng) ) + sin( radians(@center_lat) ) * sin( radians( Lat ) ) ) ) AS distance FROM table HAVING distance < @radius ORDER BY distance ASC LIMIT 0 , 20");
SqlParameter center_lat = new SqlParameter("@center_lat", SqlDbType.Decimal);
center_lat.Precision = 10;
center_lat.Scale = 6;
center_lat.Value = YOURVALUEHERE;//latitude of centre
command.Parameters.Add(center_lat);
SqlParameter center_lng = new SqlParameter("@center_lng", SqlDbType.Decimal);
center_lng.Precision = 10;
center_lng.Scale = 6;
center_lng.Value = YOURVALUEHERE;//longitude of centre
command.Parameters.Add(center_lng);
SqlParameter radius = new SqlParameter("@radius", SqlDbType.Int,3);
radius.Value = YOURVALUEHERE;
command.Parameters.Add(radius);//Radius in km
// Call Prepare after setting the Commandtext and Parameters.
command.Prepare();
command.ExecuteNonQuery();
}
}
由于我没有 MS SQL 和 C# 我无法测试
PS 用 3956 换英里 6367 换公里