计算用户与好友的距离

做社交APP,需要计算用户与好友的距离,按顺序排序

一,用mysql语句实现,最后用ROUND(,)不保留小数,四舍五入

<select id="selectAccountByIds" parameterType="com.modules.entity.QueryVo" resultMap="BaseResultMap">
     
    select
	<include refid="Base_Column_List" />
	<if test="latitude!=null and longitude!=null">
		,ROUND(( 6371 * acos ( cos ( radians(#{latitude}) )
		* cos( radians( tua.latitude ) ) * cos( radians( tua.longitude ) -
		radians(#{longitude}) )
		+ sin ( radians(#{latitude} ) ) * sin( radians( tua.latitude ) ) ) ),0)
		distance
	</if>
	from ts_user_account tua where 1=1
	<if test="circleType != null">
		and circleType = #{circleType,jdbcType=INTEGER}
	</if>
	<if test="userId!=null">
		and tua.id!=#{userId}
	</if>
	<!--不管后面的字段是升序还是降序,强制把null的放最后  -->
	<if test="latitude!=null and longitude!=null">
		ORDER BY if(isnull(distance),1,0) ,distance
	</if>
</select>  

二,java代码实现

public static double getDistance(double startlon, double startlat,double endlon, double endlat){

		double lon1 = (Math.PI / 180) * startlon;
		double lon2 = (Math.PI / 180) * endlon;
		double lat1 = (Math.PI / 180) * startlat;
		double lat2 = (Math.PI / 180) * endlat;
		double R = 6371;// 地球半径
		// 两点间距离 km,如果想要米的话,结果*1000就可以了
		return Math.acos(Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) *  Math.cos(lat2) * Math.cos(lon2 - lon1)) * R;
	}

控制舍入方式和位数

//不保留小数
new BigDecimal(d).setScale(0, BigDecimal.ROUND_HALF_UP).intValue()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值