Search by Range of coverage

Asked

Viewed 615 times

1

I am programming a site and in the advanced search has the option of the user to do a search to find places close to the city he is.

I have all the states and cities registered in the bank.

But I have no idea how to make the system know that a certain location is 6 miles from that point.

Can someone give me a light to know where to start?

Thank you.

1 answer

1

So, ideally you save the latitude and longitude of the locations that will be saved in the bank. Then, to calculate the distance between two points there are several formulas. In this link there are some formulas that you can use: https://www.movable-type.co.uk/scripts/latlong.html

I’ve been using the Spherical law of cosines. Follows the function I use, in php.


function distance($lat1, $lon1, $lat2, $lon2, $unit) {
  $theta = $lon1 - $lon2;
  $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  
cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
  $dist = acos($dist);
  $dist = rad2deg($dist);
  $miles = $dist * 60 * 1.1515;
  $unit = strtoupper($unit);

  if ($unit == "K") {
    return ($miles * 1.609344);
  } else if ($unit == "N") {
      return ($miles * 0.8684);
    } else {
        return $miles;
      }
}

Receiving as input, the latitude and longitude of each point and a char "N" to indicate that the return is in miles or "K" to indicate that the return is in meters.

If you are working with many sites, I advise you to search for a more efficient way to store locations, so you don’t have to go through all the points in the bank. Something like, nearby cities or even nearby states.

  • I’ll have to save the coordinates in the database to make the comparisons with that function there, right? I’ll test and return with the results.

  • Now explain to me how I use?

  • So, if you have the positions, just enter with the latitude and longitude of the user and with the latitude and longitude of one of the locations of the bank, the last variable the $Unit, you enter with the letter "K", the return will be the distance between the user and the chosen location.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.