Search code examples
google-mapsgoogle-maps-api-3

How to search nearby places stored in my database?


I'm developing a web app where the user sets a place in a map (Google Maps API) and I store the coordinates in a database.

At another page, I want to do a search which consists in getting my local coordinates and retrieve nearby places previously stored at my database based on a radius.

How can I do this?


Solution

  • You can use what is called the Haversine formula.

    For MySQL:

    SELECT 
      *, 
      (
        3959 * acos(
          cos(
            radians(input_lat)
          ) * cos(
            radians(lat)
          ) * cos(
            radians(lng) - radians(input_lng)
          ) + sin(
            radians(input_lat)
          ) * sin(
            radians(lat)
          )
        )
      ) AS distance 
    FROM 
      your_table 
    HAVING 
      distance < 5
    

    Where input_lat and input_lng are the coordinates of your point, and lat / lng are your table columns. The above will list the locations within a 5 miles range.

    Replace 3959 by 6371 to change to kilometers.