Java checks long lat in a 1 km circle

I am working on a Java EE a have and entity project like this:

@Entity public class Location { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long messageId; @ManyToOne private User user; private String name; private Float latitude; private Float longitude; } 

And I need to filter out these places with a central point, if they are in a circle with a diameter of 1 km.

enter image description here

I need a method that only returns locations A, B, C, E.

 public List<Location> findLocations(Float longitude, Float latitude) { List<Location> locations = entityManager.createQuery("select l from Location where ???") .setParameter("longitude", longitude) .setParameter("latitude", latitude) .getResultList(); return locations; } 

I found some code examples, but I have to iterate over all locations on db (this will really be worth it)

Is it possible to do this directly using createQuery() ?

Note. I am using MySQL

+4
source share
1 answer

Assuming a rough estimate for latlong values ​​is close to the equator, the following

  • One degree of longitude is approximately 111.32 km.
  • One degree of latitude is approximately 110.57 km

reference for values

from this we can assume that

  • 1 km from longitude 1 is 0.0089831deg
  • 1 km from a width of 1 is 0.009044deg

we can exclude most data by adding the following to the Where of you sql statement

SELECT * FROM location WHERE ( latitude BETWEEN (latValue? - 0.009044) AND (LatValue?+0.009044)) AND (longtitude BETWEEN (longValue? - 0.0089831) AND (longValue?+0.0089831));

to get a more accurate result, you still need to filter the result using the Vincenty or Haversine formula.

Edit:

Or you can also apply the Vincenty or Haversine formula directly to your request. Now, whether it is more effective, I have not tested it yet. I always make a database transaction minimal. storing and retrieving data with minimal calculations.

0
source

All Articles