views:

1638

answers:

7

this is little hard one. i have latitude and longitude and i want to pull the record from the database, which has nearest latitude and longitude by the distance, if that distance gets longer then specified one, then don't retrieve it.

Table structure:
id
latitude
longitude
place name
city
country
state
zip
sealevel
+2  A: 

You're looking for things like the haversine formula. See here as well.

There's other ones but this is the most commonly cited.

If you're looking for something even more robust, you might want to look at your databases GIS capabilities. They're capable of some cool things like telling you whether a point (City) appears within a given polygon (Region, Country, Continent).

Koobz
It is indeed the most cited, but many articles refer to old computing hardware when it comes to statements about inaccurate computing using other methods. See also http://www.movable-type.co.uk/scripts/latlong.html#cosine-law
Arjan
+5  A: 

What you need is to translate the distance into degrees of longitude and latitude, filter based on those to bound the entries that are roughly in the bounding box, then do a more precise distance filter. Here is great paper that explains how to do all this:

http://www.scribd.com/doc/2569355/Geo-Distance-Search-with-MySQL

Igor Zevaka
A: 

It sounds like you want to do a nearest neighbour search with some bound on the distance. SQL does not support anything like this as far as I am aware and you would need to use an alternative data structure such as an R-tree or kd-tree.

cdv
+1  A: 

This is sort of a duplicate of the proximity search question.

Darius Bacon
A: 

This problem is not very hard at all, but it gets more complicated if you need to optimize it.

What I mean is, do you have 100 locations in your database or 100 million? It makes a big difference.

If the number of locations is small, get them out of SQL and into code by just doing ->

Select * from Location

Once you get them into code, calculate the distance between each lat/lon and your original with the Haversine formula and sort it.

chamiltongt
i would say 100 thousands
Basit
+1  A: 

Sounds like you should just use PostGIS, SpatialLite, SQLServer2008, or Oracle Spatial. They can all answer this question for you with spatial SQL.

TheSteve0
A: 

You should try these: http://en.wikipedia.org/wiki/Great-circle_distance http://code.google.com/apis/maps/articles/phpsqlsearch.html

anhnv