Search code examples
phpmappinglatitude-longitudelogarithm

How to group the closest locations nearby given lat and long?


Imaging that I have an array of places, and each item include name, lat and long of that place. Now I want to group nearby items using a radius in miles for example.

How do I achieve this in PHP?


Solution

  • You need to have a second array to store data. And a duplicate of your array of places.

    for each $place in $places_array do
       store $place in $store_array
       for each $place2 in $places2_array do
          if $place2 == $place
             continue
          else
             if compare_radius() == true
                 store $place2 in $store_array
             end_if
          end_else
       end_for
       erase each new data in store from $places2_array  (Only if you do not want to replicate data)
    end_for
    

    Vars

    • $store_array: new array with all places group by proximity. Its structure can be sthing like [0]->[place_1][place_2], [1]->[place_1], etc...
    • $places_array: your array of data.
    • $places2_array: a duplicate from $places_array.

    I know this is not an efficient algorithm, but it does the job. If you have many data, maybe it is better to use another algorithm.