java版:
public double getDistance(Point start, Point end) {
double lon1 = (Math.PI / 180) * start.longitude;
double lon2 = (Math.PI / 180) * end.longitude;
double lat1 = (Math.PI / 180) * start.latitude;
double lat2 = (Math.PI / 180) * end.latitude;
// 地球半径
double R = 6371;
double d = Math.acos(Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1))
* R;
//转换成千米(根据自己需求)
return d * 1000;
}
sql创建计算函数代码:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[fnGetDistance](@LatBegin REAL, @LngBegin REAL, @LatEnd REAL, @LngEnd REAL) RETURNS FLOAT
AS
BEGIN
--距离(米)
DECLARE @Distance FLOAT
DECLARE @b INT SET @b = -180
DECLARE @c INT SET @c = 180
DECLARE @d INT SET @d = -74
DECLARE @e INT SET @e = 74
DECLARE @X_PI REAL SET @X_PI = 3.14159265358979323846
if(@LngBegin > @c)
begin
set @LngBegin = @LngBegin-(@c - @b)
end
if(@LngBegin < @b)
begin
set @LngBegin = @LngBegin+(@c - @b)
end
if(@LngEnd > @c)
begin
set @LngEnd = @LngEnd-(@c - @b)
end
if(@LngEnd < @b)
begin
set @LngEnd = @LngEnd+(@c - @b)
end
if(@LatBegin < @d)
begin
set @LatBegin = @d
end
if(@LatBegin > @e)
begin
set @LatBegin = @e
end
if(@LatEnd < @d)
begin
set @LatEnd = @d
end
if(@LatEnd > @e)
begin
set @LatEnd = @e
end
DECLARE @aX REAL SET @aX = @X_PI*@LngBegin/180
DECLARE @aY REAL SET @aY = @X_PI*@LatBegin/180
DECLARE @bX REAL SET @bX = @X_PI*@LngEnd/180
DECLARE @bY REAL SET @bY = @X_PI*@LatEnd/180
set @Distance = 6370996.81*ACOS(SIN(@aY)*SIN(@bY)+ COS(@aY) * COS(@bY) * COS(@bX - @aX))
RETURN @Distance
END
GO