且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

计算两点之间的距离(纬度、经度)

更新时间:2023-02-01 23:29:54

由于您使用的是 SQL Server 2008,因此您拥有 geography 数据类型可用,专为此类数据而设计:

Since you're using SQL Server 2008, you have the geography data type available, which is designed for exactly this kind of data:

DECLARE @source geography = 'POINT(0 51.5)'
DECLARE @target geography = 'POINT(-3 56)'

SELECT @source.STDistance(@target)

给予

----------------------
538404.100197555

(1 row(s) affected)

告诉我们从(近)伦敦到(近)爱丁堡约 538 公里.

Telling us it is about 538 km from (near) London to (near) Edinburgh.

自然要先学习大量的知识,但是一旦你知道它比实现你自己的Haversine计算要容易得多;此外,您还可以获得许多功能.

Naturally there will be an amount of learning to do first, but once you know it it's far far easier than implementing your own Haversine calculation; plus you get a LOT of functionality.

如果您想保留现有的数据结构,您仍然可以使用 STDistance,通过使用 Point 方法:

If you want to retain your existing data structure, you can still use STDistance, by constructing suitable geography instances using the Point method:

DECLARE @orig_lat DECIMAL(12, 9)
DECLARE @orig_lng DECIMAL(12, 9)
SET @orig_lat=53.381538 set @orig_lng=-1.463526

DECLARE @orig geography = geography::Point(@orig_lat, @orig_lng, 4326);

SELECT *,
    @orig.STDistance(geography::Point(dest.Latitude, dest.Longitude, 4326)) 
       AS distance
--INTO #includeDistances
FROM #orig dest