SQL search results by distance - mysql

I need some help, I've never done my own SQL search before and I'm trying to do this:
I have a database of names and locations (the locations are listed with a Latitude record and a Longitude record). Then, a user can search by entering their zip code (which is converted to longitude and latitude) and a distance they're willing to travel (in miles, which I can convert to lon/lat distance).
How can I return the results ordered by the distance away from their ZipCode?
Please keep in mind, I haven't ever done anything like this before.

There's a mathematical formula for figuring the shortest distance between two points on a sphere. The formula and a JS implementation of it are here:
http://www.movable-type.co.uk/scripts/latlong.html
A T-SQL implementation is here:
http://weblogs.asp.net/jimjackson/archive/2009/02/13/calculating-distances-between-latitude-and-longitude-t-sql-haversine.aspx

Related

Get close points (geometry) in MySQL

I have a MySQL database table with a series of points, which is a specific geometry data type (basically, a lat/lon coordinate). I need to get all the points that are close to some coordinates (close meaning to less that 1 km, let's say).
Now I am getting ALL points from the table and, from PHP, calculating which of them have a distance shorter than the desired distance (1 km).
The problem is that there a thousands of points, so the performance is very poor.
Is there a way to get only those close points directly from the database? I don't guess what function may help me.
Thank you!

Google maps distance matrix API: get absolute distance

I want to calculate distances between two coordinates but sometimes the origin coordinate is over / beyond the destination coordinate. And it is really problematic at one-way roads, because in this case the distance can be eg. 1 km to get back to the destination. In real life it is OK, but actually the real distance is only eg. 10 meters (if I could turn back on one-way roads). So only the direction is wrong.
I can resolve this problem if I call the API twice (origins=my_origin_coordinate&destinations=my_destination_coordinate and origins=my_destination_coordinate&destinations=my_origin_coordinate).
But is there a easier way to get both distance in one query? (to save my query limit...)
The distance matrix allows multiple results in a single query. You can do origins=my_origin_coordinate|my_destination_coordinate&desti‌​nations=my_origin_co‌​ordinate|my_destinat‌​ion_coordinate in a single request, which will give you both results. That won't really help with your quota though as the quota is based on "elements", and whether you do it in one query or two, it will be the same number of "elements".

Unsure of what to do with multiple latitudes

I'm creating a webapp where I want to do a search by radius based on latitude and longitude. However, if a user enters just they're city and state, a lot of cities will match multiple zipcodes, which in turn will match multiple latitude and longitude points. My question is, what is the recommended way to deal with multiple latitudes? Is taking the average an option? I assumed that would violate principles of distance calculation..
Typically a radius based search is done when you only have one latitude /longitude point. Otherwise, if you have multiple points then they are bound to form a polygon. You can then do bounds calculations to determine if a given point is within the boundaries of the polygon. You could also set a threshold distance outside of the polygon.

mysql: store latitude and longitude of a lot of POIs, using mysql spatial, and calculating distances

I've to create a db of a lot of restaurants in italy (>100000), and I'd like to create a "near me" function. I woud like to create a table containing latitude and longitude of all restaurants, and I've thought to use mysql spatial.
Do you have any idea of how can I create a query to find all restaurants around me (my coordinates will be taken by gps), in a 10km radius?
I'm trying to undestand distances, but googling around I haven't found anything interesting.
Do you think that using mysql spatial is a good idea? could I use float instead? in this case, how can I create a query to find all restaurants around me in a 10km radius?
Thanks a lot
The MBRIntersects or MBRContains function of MySQL spatial seems to be what you'll need to get acquainted with.
See this question's accepted answer as a start.
Asking on gis.stackexchange.com may give better answers regarding MySQL spatial specifically.
Yes, you could use the geospatial functionality - but it's rather complicated. It would be a lot simpler to just index entries based on latitude and longitude (and longitude and latitude too!). As for querying the data, I'd recommend you run queries looking for rows matching a 20km X 20km bounding box centred on the current location (which can use the indices) rather than trying to query for records which are actually within 10km - you can discard those outside the radius eksewhere in the query, e.g.
SELECT * FROM (
SELECT p.id, p.description,
SQRT((x.current_latitiude-p.latitude)*(x.current_latitiude-p.latitude)
+ (x.current_longitude-p.longitude)*(x.current_longitude-p.longitude))
AS distance
FROM places p
WHERE p.latitude BETWEEN (x.current_latitiude - x.max_range)
AND (x.current_latitiude + x.max_range)
AND p.longitude BETWEEN (x.current_longitiude - x.max_range)
AND (x.current_longitiude - x.max_range)
) ilv
WHERE ilv.distance<x.max_range
(You'll need to convert 10km into the units you're using for longitude / latitude and subsitute the value for x.max_range).

How to use MySQL geospatial extensions with spherical geometries

I would like to store thousands of latitude/longitude points in a MySQL db. I was successful at setting up the tables and adding the data using the geospatial extensions where the column 'coord' is a Point(lat, lng).
Problem:
I want to quickly find the 'N' closest entries to latitude 'X' degrees and longitude 'Y' degrees. Since the Distance() function has not yet been implemented, I used GLength() function to calculate the distance between (X,Y) and each of the entries, sorting by ascending distance, and limiting to 'N' results. The problem is that this is not calculating shortest distance with spherical geometry. Which means if Y = 179.9 degrees, the list of closest entries will only include longitudes of starting at 179.9 and decreasing even though closer entries exist with longitudes increasing from -179.9.
How does one typically handle the discontinuity in longitude when working with spherical geometries in databases? There has to be an easy solution to this, but I must just be searching for the wrong thing because I have not found anything helpful.
Should I just forget the GLength() function and create my own function for calculating angular separation? If I do this, will it still be fast and take advantage of the geospatial extensions?
Thanks!
josh
UPDATE:
This is exactly what I am describing above. However, it is only for SQL Server. Apparently SQL Server has a Geometry and Geography datatypes. The geography does exactly what I need. Is there something similar in MySQL?
How does one typically handle the discontinuity in longitude when working with spherical geometries in databases?
Not many people use MySQL for this, because it's geospatial extensions aren't really up to snuff.
From the docs:
"All calculations are done assuming Euclidean (planar) geometry."
The solution is usually to roll your own.
Alternatively, you can fake it -- if your distances are less than a 500 miles or so, then you can treat your latitude and longitude as rectangular coordinates and just use the euclidean distance formula (sqrt(a^2 + b^2)).