1、数据库创建经纬度的函数
CREATE OR REPLACE FUNCTION FUN_JW_DIST(lng1 numeric, lat1 numeric, lng2 numeric, lat2 numeric) RETURNS numeric AS $$ SELECT ceil(( 6371 * acos( cos(radians(lat1)) * cos(radians(lat2)) * cos( radians(lng1) - radians(lng2) ) + sin(radians(lat1)) * sin(radians(lat2)) ) )*1000)::numeric as dist; $$ LANGUAGE SQL;
调用
select FUN_JW_DIST(120.451737, 36.520975, 120.455636, 36.520885) as dist;
返回的dist即为距离
2、Java计算
引入Jar
<dependency> <groupId>org.gavaghan</groupId> <artifactId>geodesy</artifactId> <version>1.1.3</version> </dependency>
进行计算
/** * 计算实际距离 * * @param longitudeFrom 距离1的经度 * @param latitudeFrom 距离1的纬度 * @param longitudeTo 距离2的经度 * @param latitudeTo 距离2的纬度 * @return 实际距离,单位:米(四舍五入为整数) */ public static long getDistance(double longitudeFrom, double latitudeFrom, double longitudeTo, double latitudeTo) { GlobalCoordinates source = new GlobalCoordinates(latitudeFrom, longitudeFrom); GlobalCoordinates target = new GlobalCoordinates(latitudeTo, longitudeTo); return Math.round(new GeodeticCalculator().calculateGeodeticCurve(Ellipsoid.Sphere, source, target).getEllipsoidalDistance()); }