如何获取一个圈内的所有数据?

How to get all the data in a circle?

我有一个 table,其中包含列名称、纬度和经度。我想找到一个圆圈内的所有数据,按离中心点最近的距离排序。为了得到圆,我有一个中心点 (latitude/longtitude)。假设纬度和经度是-6.12579106和106.65699005,那么将出现的数据是名称为A和B的数据。下面是我的table(意外table)

name, latitude, longtitude
A, -6.13116749, 106.66625977
B, -6.10377274, 106.66703224
C, 3.5896654,   98.6738261

我想在 WHERE CLUASE 中按最近距离查找数据。怎么做?感谢您的帮助:)

SELECT * FROM accident
LEFT JOIN polres ON polres.id = accident.polres_id
LEFT JOIN polda ON polda.id = polres.polda_id
WHERE --(condition for find data by closest distance) 

您可以使用以下函数计算距离:

CREATE OR REPLACE FUNCTION calculate_distance(lat1 float, lon1 float, lat2 float, lon2 float, units varchar)
RETURNS float AS $dist$
    DECLARE
        dist float = 0;
        radlat1 float;
        radlat2 float;
        theta float;
        radtheta float;
    BEGIN
        IF lat1 = lat2 OR lon1 = lon2
            THEN RETURN dist;
        ELSE
            radlat1 = pi() * lat1 / 180;
            radlat2 = pi() * lat2 / 180;
            theta = lon1 - lon2;
            radtheta = pi() * theta / 180;
            dist = sin(radlat1) * sin(radlat2) + cos(radlat1) * cos(radlat2) * cos(radtheta);

            IF dist > 1 THEN dist = 1; END IF;

            dist = acos(dist);
            dist = dist * 180 / pi();
            dist = dist * 60 * 1.1515;

            IF units = 'K' THEN dist = dist * 1.609344; END IF;
            IF units = 'N' THEN dist = dist * 0.8684; END IF;

            RETURN dist;
        END IF;
    END;
$dist$ LANGUAGE plpgsql;

对于units参数,您可以使用以下值:

'M' is statute miles (default)                     
'K' is kilometers
'N' is nautical miles

然后按如下方式使用上面的函数:

SELECT * from test where 
calculate_distance(latitude, longtitude, -6.12579106, 106.65699005, 'K') <3;