Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to efficiently calculate which points are close to a given lat/long using MySQL?

I'm trying to design a MySQL schema that can store a list of users with an associated latitude and longitude.

I would then, for a given user, like to build a query which can return the nearest 50 users to him/her and sort those users by distance (with the nearest being presented first).

Given that there may be many thousands of users in this table, what is the most efficient way to store and query this data?

like image 582
Andrew J Avatar asked Jun 30 '10 23:06

Andrew J


People also ask

How do I find the closest location using latitude and longitude in MySQL?

To find locations in your markers table that are within a certain radius distance of a given latitude/longitude, you can use a SELECT statement based on the Haversine formula. The Haversine formula is used generally for computing great-circle distances between two pairs of coordinates on a sphere.

How can I find the distance between two points in MySQL?

Calculating Distance in MySQL To get the distance between two points, you call the function with the two points as the arguments: -- Returns distance in meters.


2 Answers

Try reading this article: Creating a Store Locator with PHP, MySQL & Google Maps That article shows a MySQL solution for the Haversine formula, which is the best way to compute distance given latitude and longitude.

like image 85
Bill Karwin Avatar answered Oct 04 '22 06:10

Bill Karwin


Take a look at MySql's spatial indexing.

You can also use the Great Circle Distance, there is a good SO article on it here.

like image 42
Abe Miessler Avatar answered Oct 04 '22 07:10

Abe Miessler