I have a file that changes every now and then which contains gps coordinates. I would like to get the country in which those coordinates fall. Software should be running on a headless debian 8 machine and produce a plain text output.


As indicated in this answer you can use Google's Geocoding API which returns a json string. Based on this answer I created a script that returns a country - if there is one - based on the coordinates:

import sys
import urllib, json

if len(sys.argv)<2:
    print("Requires parameters: longitude latitude")

def locToCountry(coord_long,coord_lat):
    # create url and open
    url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=%s,%s&sensor=true" % (coord_long,coord_lat)
    response = urllib.urlopen(url)
    data = json.loads(response.read())

    # check if there is data
    if len(data['results'])==0:
        print("ERROR: no country found")
        return ""

    # print data
    subdata =  data['results'][0]['address_components']

    # search for the country name
    for d in subdata:
        if 'country' in d['types']:
            return d["long_name"]

    print("WARNING: no country found")
    return ""

# call function
country = locToCountry(sys.argv[1],sys.argv[2])
# print on screen
print("%s, %s => %s" % (sys.argv[1],sys.argv[2],country))

Now you can run the script and it return the name of the country (if there is one):

> loctocountry.py 43 -3 
43, -3 => Spain
> loctocountry.py 40.7 -73.9
40.7, -73.9 => United States

Not the answer you're looking for? Browse other questions tagged or ask your own question.