Find users within a distance by using Latitude, Longitude, and MySQL

For filter records, you need to latitude and longitude column in the table which you are using. For fetching data as per the lat-long you can use below query by passing latitude and longitude values in the comments.

In this below query, the user table is used and there is 2 latitude and longitude. One is for the user and we will get it from the user and others commented we need to pass to fetch data of users as per that particular area.

    3959 * acos(
      cos(radians('--Here--')) * cos(radians(`users`.latitude)) * cos(
        radians(`users`.longitude) - radians(--Longitude Here--)
      ) + sin(radians(--Latitude Here--)) * sin(radians(`users`.latitude))
  ) AS distance
  `distance` < 10
  `distance` ASC

In which limit also used. If you also want to use that’s ok if you not want limit you can remove that limit code to fetch all data. Also in this, we have used the order by distance so the nearby user’s data comes first and then far users.

Leave a Reply

Your email address will not be published. Required fields are marked *