This may or may not be clear, leave me a comment if I am off base, or you need more information. Perhaps there is a solution out there already for what I want in PHP.
I am looking for a function that will add or subtract a distance from a longitude OR latitude value.
Reason: I have a database with all Latitudes and Longitudes in it and want to form a query to extract all cities within X kilometers (or miles). My query would look something like this...
Select * From Cities Where (Longitude > X1 and Longitude < X2) And (Latitude > Y1 and Latitude < Y2)
Where X1 = Longitude - (distance)
Where X2 = Longitude + (distance)
Where Y1 = Latitude - (distance)
Where Y2 = Latitude + (distance)
I am working in PHP, with a MySql Database.
Open to any suggestions also! :)
There are many (bad options)
Calculate the distance using the mathematical formula (treat X1-X2 and Y1-Y2) as vectors.
Create a lookup table in advance with all the combinations and keep the distances.
Consider using a GIS-specific extension of MySQL. Here is one article I found about this.
This is a MySQL query that will do exactly what you want. Keep in mind things like this are approximations generally, as the earth is not perfectly spherical nor does this take into account mountains, hills, valleys, etc.. We use this code on AcademicHomes.com with PHP and MySQL, it returns records within $radius miles of $latitude, $longitude.
lessthandot.com actually has 3 different ways to do this. you'll have to scroll through the blogs a little but they're there. http://blogs.lessthandot.com/
The function below is from the nerddinner's (ASP.NET MVC sample application available on codeplex) database (MSSQL).
I am guessing this could be helpful.
Don't reinvent the wheel. This is a spatial query. Use MySQL's built-in spatial extensions to store the latitude-longitude coordinate data in the native MySQL geometry column type. Then use the Distance function to query for points that are within a specified distance of one another.
Disclaimer: this is based on reading the documentation, I haven't tried this myself.
Using the setup from the following URL, Ive built the query below. (Please note Im using codeIgnitor to query the database)
http://howto-use-mysql-spatial-ext.blogspot.com/2007/11/using-circular-area-selection.html