0

I am trying to calculate the distance between several users based on their long/lat. I am using Spring JPA and PostgreSQL.

This is my Repository-class:

public interface UserWithCoordinateRepository extends JpaRepository<UserWithCoordinate, UUID> {

String HAVERSINE_FORMULA = "(6371 * acos(cos(radians(?2)) * cos(radians(uwc.latitude)) *" +
    " cos(radians(uwc.longitude) - radians(?1)) + sin(radians(?2)) * sin(radians(uwc.latitude))))";

@Query("SELECT uwc FROM UserWithCoordinate uwc WHERE " + HAVERSINE_FORMULA + " < ?3 ORDER BY " + HAVERSINE_FORMULA + " DESC")
List<UserWithCoordinate> findByCoordinates(double longitude, double latitude, double distance, Pageable pageable);
}

But I keep getting this error: org.postgresql.util.PSQLException: ERROR: Input is out of range!

I already went through these articles:

But I am not able to fix my issue.

TheWieand
  • 253
  • 3
  • 18

1 Answers1

0

I found another formula that works as expected:

111.045* DEGREES(ACOS(LEAST(1.0, COS(RADIANS(latpoint))
             * COS(RADIANS(latitude))
             * COS(RADIANS(longpoint) - RADIANS(longitude))
             + SIN(RADIANS(latpoint))
             * SIN(RADIANS(latitude)))))

Maybe someone will find it useful :)

TheWieand
  • 253
  • 3
  • 18