4

I'm working on a Java EE project an have and entity 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 these locations with a center point if they are in 1 km diameter circle.

enter image description here

I need a method like this returning only A, B, C, E locations.

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 samples, but I must iterate over all locations on db (this will be really costed)

Can I do it directly with createQuery()?

Note: I'm using MySQL

Erdinç Özdemir
  • 1,363
  • 4
  • 24
  • 52
  • 1
    http://stackoverflow.com/questions/13026675/calculating-distance-between-two-points-latitude-longitude – Marc B Aug 04 '15 at 18:46
  • which database system do you use? – sinclair Aug 04 '15 at 18:49
  • It's been a while since I was in this topic and I uses Postgres/PostGIS. For MySQL this could solve your problem: http://www.cubrid.org/blog/dev-platform/20-minutes-to-understanding-spatial-database/ – sinclair Aug 04 '15 at 18:54

1 Answers1

0

assuming for a rough estimate for the latlong values are near the equator are the following

  • One degree of longitude is roughly 111.32 km
  • One degree of latitude is roughly 110.57 km

reference for values

from this we can assume that

  • 1km of longtitude 1 is equal to 0.0089831deg
  • 1km of latitude 1 is equal to 0.009044deg

we can eliminate the majority of the data by the 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 resulting value with either Vincenty or Haversine formula.

Edit:

Or you could also implement Vincenty or Haversine formula directly to your query. now whether it is more efficient to do so, I haven't tested yet. I always keep my database transaction to a minimal. storing and retrieving data with very minimal computations.

lababo
  • 114
  • 5