I'm developing a search for favorite places using the Mapbox and Google Maps APIs.
At the moment I use the haversine formula to realize a circular search starting from a point. For example, when I click on a state on the map this returns me a latitude and longitude of the state as such (the center of the state exactly or the country) and also returns me the latitude and longitude of each cardinal point (North South East West) by the haversine formula I calculate the distance between the center and each one of the points and with that I get an average distance with PHP.
math class
{
const radius = 6371;
public function __construct ()
{
}
public function harversine ($ lat, $ lng, $ lat2, $ lng2)
{
$ d = 0;
$ t1 = deg2rad ($ lat);
$ t2 = deg2rad ($ lat2);
$ dt = deg2rad (($ lat2 - $ lat));
$ dl = deg2rad (($ lng2 - $ lng));
$ a = (sin ($ dt / 2) * sin ($ dt / 2)) +
(cos ($ t1) * cos ($ t2)) *
(sin ($ dl / 2)) sin ($ dl / 2));
$ c = 2 * atan2 (sqrt ($ a), sqrt ((1 - $ a)));
$ d = self :: radius * $ c;
return floor ($ d);
}
}
Now, with this average distance, I do a search in the database based on that distance to find places that I have stored with their respective coordinates that are my favorites, within the base I calculate the formula again.
Everything is perfect, the problem is the circular search and is not limited to passing another state if the distance identifies it that way, I explain a little more with an example.
If I look for Tlapa, Guerrero State, Mexico and process the search, this search is done in circular shape at a distance X (from the center).
I will bring all the places if they are on the circle area, the problem is, it passes from the demarcations of the State of Guerrero and thus no longer works with my App.
I say, I made the search within the limitations of the state, without going through another state but respecting the distance of the search, in this example 50KM, it will continue searching the West and Southwest but no longer beyond North-East and Northeast.
Does exist any Google or Mapbox API whose bring me these boundaries or how can I calculate them?