I have an entitiy which has two columns in the database like this:
@Column(name = "latitude", nullable = false)
private float currentPositionLatitude;
@Column(name = "longitude", nullable = false)
private float currentPositionLongitude;
And I have multiple entrys in my database(PostgresQl) for the entity with different latitudes and longitudes for all of them. Now I want to give a point (lat,lon) and a radius and show all entitys which are near the point. I first tried it with the Harversine formula like this in Spring Jpa :
String HAVERSINE_PART = "(6371 * acos(cos(radians(:latitude)) * cos(radians(s.latitude)) *" +
" cos(radians(s.longitude) - radians(:longitude)) + sin(radians(:latitude)) * sin(radians(s.latitude))))";
@Query("SELECT currentPositionLatitude,currentPositionLongitude FROM Entity WHERE '%:HAVERSINE_PART%' < :distance ORDER BY '%:HAVERSINE_PART%' DESC")
public List<Entity> findEntiryWithLocation(
@Param("currentPositionLatitude") final float latitude,
@Param("currentPositionLongitude") final float longitude, @Param("distance") final double distance )
this didnt work so I tried:
@Query("SELECT s FROM Entity s WHERE " + HAVERSINE_PART + " < :distance ORDER BY "+ HAVERSINE_PART + " DESC")
List<Entity> findEntityWithInDistance(
@Param("latitude") double latitude,
@Param("longitude") double longitude,
@Param("distance") double distanceWithInKM );
this also didnt work so then I tried:
@Query(value = "SELECT *, earth_distance(ll_to_earth(:latitude, :longitude), ll_to_earth(latitude, longitude)) as distance FROM Car WHERE (earth_box(ll_to_earth(:latitude, :longitude), :radiusInMeters) @> ll_to_earth(latitude, longitude))ORDER BY distance ASC",
nativeQuery = true)
List<Entity> getPlacesNear ( @Param("latitude") float latitude,
@Param("longitude")float longitude,
@Param("radiusInMeters") float radiusInMeters);
This compiled but when I tried to put in values in my controller I got the error: jdbc error :2022 no dialect mapping
Here my methods for the service and the controller(the datatypes have changed maybe):
public List<Entity>showNearestEntityByDistances(float latitude, float longitude, float distance){
return EntityRepository.getPlacesNear(latitude,longitude,distance);
}
and the endpoint:
@GetMapping("/location")
public List<Entity>showEntityNearby(@RequestParam float latitude,@RequestParam float longitude,@RequestParam float distance){
return carService.showNearestEntitysByDistances(latitude,longitude,distance);
}
I already looked at : https://www.postgresql.org/docs/current/earthdistance.html and postgresql jpa earth_distance query
but it didnt worked. Has anyone an idea what Im doing wrong ? Thanks in regard.