mysql通过经纬度计算两点距离

传入参数 纬度 23.163292 经度 113.3114676
与数据库中经纬度对比,得到距离
在这里插入图片描述

计算公式有点复杂,先上sql:

SELECT
		bm.`id`         id,
		bm.`bus_name` busname,
		bm.`bus_logo` bus_logo,
		bm.`address` address,
		bm.`latitude` latitude,
		bm.`longitude` longitude,
		ROUND(
			6378.138 * 2 * ASIN(
				SQRT(
					POW( SIN( ( 23.163292 * PI() / 180 - bm.`latitude` * PI() / 180 ) / 2 ), 2 ) + COS( 23.163292 * PI() / 180 ) * COS( bm.`latitude` * PI() / 180 ) * POW( SIN( ( 113.3114676 * PI() / 180 - bm.`longitude` * PI() / 180 ) / 2 ), 2 ) 
				) 
			) * 1000 
		) distance 
	FROM
		`bus_manage` bm 
	ORDER BY
	distance ASC

查询结果:
在这里插入图片描述

但是在swagger中,没有distance
在这里插入图片描述
把这个表作为临时表,修改sql:

SELECT
	temp.`busname`,
	temp.`bus_logo`,
	temp.`address`,
	temp.`latitude`,
	temp.`longitude`,
	temp.`distance` 
FROM
	(
	SELECT
		bm.`bus_name` busname,
		bm.`bus_logo` bus_logo,
		bm.`address` address,
		bm.`latitude` latitude,
		bm.`longitude` longitude,
		ROUND(
			6378.138 * 2 * ASIN(
				SQRT(
					POW( SIN( ( 23.163292 * PI() / 180 - bm.`latitude` * PI() / 180 ) / 2 ), 2 ) + COS( 23.163292 * PI() / 180 ) * COS( bm.`latitude` * PI() / 180 ) * POW( SIN( ( 113.3114676 * PI() / 180 - bm.`longitude` * PI() / 180 ) / 2 ), 2 ) 
				) 
			) * 1000 
		) distance 
	FROM
		`bus_manage` bm 
	ORDER BY
	distance ASC 
	) AS temp

成功查出所有字段:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_42260782/article/details/114541797