不使用三角函数的 SQL 距离查询
我有一个 SQLite 数据库,它不支持三角函数。我想按距离对表中的一组纬度、经度对进行排序,并与第二个纬度、经度对进行比较。我熟悉用于按距离对 lat,lng 对进行排序的标准半正矢距离公式。
在这种情况下,我并不特别关心精度,我的点相距很远,所以我不介意通过将曲线视为直线来舍入距离。
我的问题是,这种查询有普遍接受的公式吗?记住不要有三角函数!
I have an SQLite database, which does not support trig functions. I would like to sort a set of lat,lng pairs in my table by distance as compared to a second lat,lng pair. I'm familiar with the standard haversine distance formula for sorting lat,lng pairs by distance.
In this case I don't care particularly for precision, my points are separated by large distances, so I don't mind rounding off the distances by treating curves as straight lines.
My question, is there a generally accepted formula for this kind of query? Remember no trig functions!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您的点彼此之间的距离在合理范围内(即不跨越半个地球,也不跨越日期变更线),您可以对纬度和经度之间的差异进行修正(因为经度较短,赤道除外) ),然后就像地球是平的一样计算距离。
由于您只想对值进行排序,因此您甚至不必使用平方根,只需添加差值的平方即可。
例如,其中
@lat
和@lng
是您的当前位置,2
是差异校正:您可以计算特定的差异校正纬度为
1 / cos(lat)
。Cees Timmerman 提出了这个公式,它也适用于跨越日期变更线:
If your points are within reasonable distance of each other (i.e. not across half the world, and not across the date line), you can make a correction for the difference between latitude and longitude (as a longitude degree is shorter, except at the Equator), and then just calculate the distance as if the earth was flat.
As you just want to sort the values, you don't even have to use the square root, you can just add the squares of the differences.
Example, where
@lat
and@lng
is your current position, and2
is the difference correction:You can calculate the difference correction for a specific latitude as
1 / cos(lat)
.Cees Timmerman came up with this formula which also works across the date line:
如果您希望模型中包含正确的空间数据,请使用 SpatiaLite,这是 SQLite 的空间支持版本:
http:// /www.gaia-gis.it/spatialite/
就像 PostGIS 是针对 PostgreSQL 的。您的所有 SQLite 功能都将完美运行且不会发生变化,并且您还将获得空间函数。
If you want proper spatial data in your model then use SpatiaLite, a spatially-enabled version of SQLite:
http://www.gaia-gis.it/spatialite/
Its like PostGIS is for PostgreSQL. All your SQLite functionality will work perfectly and unchanged, and you'll get spatial functions too.
您始终可以截断正弦的泰勒级数展开式,并使用 sin^2( x)+cos^2(x)=1 得到余弦的近似值。唯一棘手的部分是使用泰勒定理来估计您需要的项数给定的精度。
You could always truncate the Taylor series expansion of sine and use the fact that sin^2(x)+cos^2(x)=1 to get the approximation of cosine. The only tricky part would be using Taylor's theorem to estimate the number of terms that you'd need for a given amount of precision.
将“*”更改为“/”对我有用:
选择*
从积分
排序依据 (lat - @lat) * (lat - @lat) + ((lng - @lng) / 2) * ((lng - @lng) / 2)
Change "*" with "/" works for me:
select *
from Points
order by (lat - @lat) * (lat - @lat) + ((lng - @lng) / 2) * ((lng - @lng) / 2)