Reputation: 43919
I have a User Model and every user is having latitude and longitude stored in the table. I want to fetch all the users in the range of 30kms with a given latitude and longitude. Any plugin to calculate the distance using latitude and longitude from the table.
id name latitude longitude
1 abc 43.56 56.34
2 xyz 46.34 57.87
3 mno 50.34 23.56
Assume this is my table values(its just a sample data.). I want to fetch all the users within a range of 30kms from a given altitude like (34.89, 56.45)
Upvotes: 0
Views: 3252
Reputation: 451
Using the help from Movable-Type Scripts that Wicked posted i made this calculate the distance between 2 points (use method in an Active Record that has lat,lng attributes):
def calc_distance(origin)
radius = 6371
lat1 = to_rad(origin[0])
lat2 = to_rad(self.lat)
lon1 = to_rad(origin[1])
lon2 = to_rad(self.lng)
dLat = lat2-lat1
dLon = lon2-lon1
a = Math::sin(dLat/2) * Math::sin(dLat/2) +
Math::cos(lat1) * Math::cos(lat2) *
Math::sin(dLon/2) * Math::sin(dLon/2);
c = 2 * Math::atan2(Math::sqrt(a), Math::sqrt(1-a));
d = radius * c
end
def to_rad angle
angle * Math::PI / 180
end
Geokit is very robust but I only needed to calculate distance, plus Geokit requires a non sqlite db
Upvotes: 1
Reputation: 7388
There is beautiful Geokit gem that add this method to your models:
Store.find(:all, :origin =>[37.792,-122.393], :within=>10)
or even
Store.find(:all, :origin=>'100 Spear st, San Francisco, CA', :within=>10)
Upvotes: 3
Reputation: 6046
Thinking sphinx has search, sort and filtering by distance from a latitude and longitude: http://freelancing-god.github.com/ts/en/geosearching.html
Upvotes: 1
Reputation: 1118
Try this link. There is a detailed explanation of the approach.
http://www.movable-type.co.uk/scripts/latlong.html
Also, I found this C# algorithm online. I hope it helps.
class DistanceAlgorithm
{
const double PIx = 3.141592653589793;
const double RADIO = 6378.16;
/// <summary>
/// This class cannot be instantiated.
/// </summary>
private DistanceAlgorithm() { }
/// <summary>
/// Convert degrees to Radians
/// </summary>
/// <param name="x">Degrees</param>
/// <returns>The equivalent in radians</returns>
public static double Radians(double x)
{
return x * PIx / 180;
}
/// <summary>
/// Calculate the distance between two places.
/// </summary>
/// <param name="lon1"></param>
/// <param name="lat1"></param>
/// <param name="lon2"></param>
/// <param name="lat2"></param>
/// <returns></returns>
public static double DistanceBetweenPlaces(
double lon1,
double lat1,
double lon2,
double lat2)
{
double dlon = lon2 - lon1;
double dlat = lat2 - lat1;
double a = (Math.Sin(dlat / 2) * Math.Sin(dlat / 2)) + Math.Cos(lat1) * Math.Cos(lat2) * (Math.Sin(dlon / 2) * Math.Sin(dlon / 2));
double angle = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));
return angle * RADIO;
}
Upvotes: 0