计算用户与好友的距离

做社交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>
	<if test="latitude!=null and longitude!=null">
		ORDER BY 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()

猜你喜欢

转载自blog.csdn.net/qq_39308071/article/details/82020050