博客园  :: 首页  :: 联系 :: 管理

Sqlserver 计算两坐标距离函数

Posted on 2018-12-15 11:22  天戈朱  阅读(1524)  评论(0编辑  收藏  举报

mark

if exists (select * from dbo.sysobjects where id = object_id(N'UF_ETL_GetDistance') and xtype in (N'FN', N'IF', N'TF'))
    drop function UF_ETL_GetDistance
GO

CREATE FUNCTION UF_ETL_GetDistance
( 
   @sLng    DECIMAL(12,6),
   @sLat    DECIMAL(12,6),
   @eLng    DECIMAL(12,6),
   @eLat    DECIMAL(12,6)
)
RETURNS DECIMAL(12,4)
AS
BEGIN
   DECLARE @result DECIMAL(12,4)
   SELECT @result = 6378137.0*ACOS(SIN(@sLat/180*PI())*SIN(@eLat/180*PI())+COS(@sLat/180*PI())*COS(@eLat/180*PI())*COS((@sLng-@eLng)/180*PI()))
   RETURN @result/1000
END
go

 

二、给出坐标,计算给定距离,计算外切正方形相交的点坐标

// 将角度转换为弧度
    private static double deg2rad(double degree) {
        return degree * Math.PI / 180.0;
    }

    // 将弧度转换为角度
    static double rad2deg(double radian) {
        return radian * 180 / Math.PI;
    }

/**

 * 计算某个经纬度的周围某段距离的正方形的四个点
 * 地球半径,平均半径为6371km
 * @param lng float 经度
 * @param lat float 纬度
 * @param distance float 该点所在圆的半径,该圆与此正方形内切,默认值为0.5千米
 * @return array 正方形的四个点的经纬度坐标
 */
 function returnSquarePoint($lng, $lat,$distance = 0.5){
  
    $dlng =  2 * asin(sin($distance / (2 * 6371)) / cos(deg2rad($lat)));
    $dlng = rad2deg($dlng);
      
    $dlat = $distance/6371;
    $dlat = rad2deg($dlat);
      
    return array(
                'left-top'=>array('lat'=>$lat + $dlat,'lng'=>$lng-$dlng),
                'right-top'=>array('lat'=>$lat + $dlat, 'lng'=>$lng + $dlng),
                'left-bottom'=>array('lat'=>$lat - $dlat, 'lng'=>$lng - $dlng),
                'right-bottom'=>array('lat'=>$lat - $dlat, 'lng'=>$lng + $dlng)
                );
 }