经纬度计算距离在HQL中应用实例

本文介绍了一种基于经纬度计算两点间距离的Java方法,并提供了一个查询指定范围内地点列表的应用实例。通过数学公式和数据库查询相结合的方式,实现了对地点的有效筛选与排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

根据给定地点的经纬度(longitude,latitude),查询给定范围(distance)内的对象列表,由近及远。

java计算公式:

    def lat1 = 32.361403
    def lat2 = 40.245992
    def lng1 = 118.78418
    def lng2 = 116.477051
   double EARTH_RADIUS = 6378.137; //地球半径
   double radLat1 = lat1* Math.PI / 180.0
   double radLat2 = lat2* Math.PI / 180.0
   double a = radLat1 - radLat2;
   double b = lng1* Math.PI / 180.0 - lng2* Math.PI / 180.0
   double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
    Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
   s = s * EARTH_RADIUS;
   s = Math.round(s * 10000) / 10000;
   return s

 

实例:

  List<Place> getClosestPlacesByLatitudeAndLongitude(Double distance, String pageId, Double latitude, Double longitude, int offset, int length) {
    def placeList = []
    if (pageId) {
      def page = accountService.getContentProviderForPage(pageId)
      if (!page?.rewardsEnabled) {
        return new ArrayList()
      }
      placeList = Place.executeQuery("from Place as p where p.contentProvider =:page and (asin(sqrt(pow(sin((p.latitude - :latitude) * 3.1415926 / 360), 2) + cos(p.latitude * 3.1415926 / 180) * cos(:latitude * 3.1415926 / 180) * pow(sin((p.longitude - :longitude) * 3.1415926 / 360), 2)))*12756274) < :distance Order by (asin(sqrt(pow(sin((p.latitude - :latitude) * 3.1415926 / 360), 2) + cos(p.latitude * 3.1415926 / 180) * cos(:latitude * 3.1415926 / 180) * pow(sin((p.longitude - :longitude) * 3.1415926 / 360), 2)))*12756274) asc name asc", [distance:distance, page: page, latitude: latitude, longitude: longitude, max: length, offset: offset])
    } else {
      placeList = Place.executeQuery("from Place as p where (asin(sqrt(pow(sin((p.latitude - :latitude) * 3.1415926 / 360), 2) + cos(p.latitude * 3.1415926 / 180) * cos(:latitude * 3.1415926 / 180) * pow(sin((p.longitude - :longitude) * 3.1415926 / 360), 2)))*12756274) < :distance  Order by (asin(sqrt(pow(sin((p.latitude - :latitude) * 3.1415926 / 360), 2) + cos(p.latitude * 3.1415926 / 180) * cos(:latitude * 3.1415926 / 180) * pow(sin((p.longitude - :longitude) * 3.1415926 / 360), 2)))*12756274) asc name asc", [distance:distance, latitude: latitude, longitude: longitude, max: length, offset: offset])
    }
    return placeList
  }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值