Pregunta

I have a list of ISO 3166 country codes (240) and a list of 8 countries/territories/regions (Australia, Denmark, Netherlands, Qatar, South Africa, UAE, UK & USA). I would like to go through the list of country codes and, for each one, work out which is the closest one from the list of 8. The metric (geographical distance, straight-line distance, driving time, etc.) isn't particularly important as it doesn't need to be perfect, just reasonable.

The list of 8 places is subject to regular change so it's impractical to do the task manually. I've tried using the Google Maps API but have so far been unsuccessful. The ideal solution would be in PHP and would result in an array with the country code as the index and closest country (from the list of 8) as the value. Any help appreciated!

¿Fue útil?

Solución

The geonames project has public data that you can use

http://www.geonames.org/

Now you can get the distance between geographical coorindates.

function distance($lat1, $lng1, $lat2, $lng2, $miles = true)
{
    $pi80 = M_PI / 180;
    $lat1 *= $pi80;
    $lng1 *= $pi80;
    $lat2 *= $pi80;
    $lng2 *= $pi80;

    $r = 6372.797; // mean radius of Earth in km
    $dlat = $lat2 - $lat1;
    $dlng = $lng2 - $lng1;
    $a = sin($dlat / 2) * sin($dlat / 2) + cos($lat1) * cos($lat2) * sin($dlng / 2) * sin($dlng / 2);
    $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
    $km = $r * $c;

    return ($miles ? ($km * 0.621371192) : $km);
}

For your use case you could use the capital of the countries. For big countries you should possibly add some more countries near the boarders.

That is one solution. You could also store geometric shapes that approximate the country in a database and make exact queries...

However the starting point is the data. What do you actually want? What data do you have?

If efficiency is a problem I would recommend build a graph where every country is stored and linked with its border countries. If you only look at the border countries this greatly reduces computational effort.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top