Search code examples
pythonpython-3.xrequestgeolocationpython-requests

If I have a set of coordinates, how can I get the country, only with the Requests library?


I need to get the country from which a set of coordinates are from: example:

coords=[41.902782, 12.496366.]


output:

Italy

I know that this can be made by using other libraries, but I need to know if there's a way to do it only with the requests library.(json is available too) Thanks.


Solution

  • As @Razdi has said, you will need an API that takes your coordinates and returns a location.

    This is called reverse geocoding.

    Think of the Requests library like a browser URL path. All it can do is get an address of a website. However, if the address is right, and expects certain parameters, then you can access values:

    >>> import requests
    >>> url = 'https://maps.googleapis.com/maps/api/geocode/json'
    >>> params = {'sensor': 'false', 'address': 'Mountain View, CA'}
    >>> r = requests.get(url, params=params)
    >>> results = r.json()['results']
    >>> location = results[0]['geometry']['location']
    >>> location['lat'], location['lng']
    

    What you want is something like this:

    import geocoder
    g = geocoder.google([45.15, -75.14], method='reverse')
    

    But you're not allowed to use the package... so you'll need to be more verbose:

    import requests

    def example():
        # grab some lat/long coords from wherever. For this example,
        # I just opened a javascript console in the browser and ran:
        #
        # navigator.geolocation.getCurrentPosition(function(p) {
        #   console.log(p);
        # })
        #
        latitude = 35.1330343
        longitude = -90.0625056
    
        # Did the geocoding request comes from a device with a
        # location sensor? Must be either true or false.
        sensor = 'true'
    
        # Hit Google's reverse geocoder directly
        # NOTE: I *think* their terms state that you're supposed to
        # use google maps if you use their api for anything.
        base = "http://maps.googleapis.com/maps/api/geocode/json?"
        params = "latlng={lat},{lon}&sensor={sen}".format(
            lat=latitude,
            lon=longitude,
            sen=sensor
        )
        url = "{base}{params}".format(base=base, params=params)
        response = requests.get(url)
        return response.json()['results'][0]['formatted_address']
    

    Code snippet taken and modified from here.