Sometimes we need to calculate the distance between two locations. And to save the time of iteration we can get filtered results through query by apply functionality of calculating distance in the query.
Suppose we have two tables Events and User, and we want to display only those events that fall under the user's geographical area lets say within 50 miles. Both table should have latitude and longitude as columns.
Write the following code to get filtered data by distance:
// Here you will pass user's lat/long as argument
public List<Events> getAllEvents(double latitud, double longitude) {
List<Events> eventsList = null;
String hqlQuery = "select a from Events a where a.event_date >= :currentDate and (((acos(sin(((:latitude)*pi()/180)) * sin((a.latitude*pi()/180))+cos(((:latitude)*pi()/180)) * cos((a.latitude*pi()/180)) * cos((((:longitude)- a.longitude)*pi()/180))))*180/pi())*60*1.1515) <=50 ";
try {
Query query = sessionFactory.getCurrentSession().createQuery(
hqlQuery);
query.setDouble("latitude", latitud);
query.setDouble("longitude", longitude);
eventsList = (List<Events>) query.list();
} catch (Exception e) {
e.printStackTrace();
}
return eventsList;
}
Hope this will help you :)
0 Comment(s)