3

Is there any open source GIS function in python to get lat lon window given only country name. Something like:

get_country_window('United states of america')

should return:

[-135, -50, 22, 50]
  • Do you mean the center coordinates ? – Shiko Oct 3 '16 at 8:50
  • @Shady, no I mean the corner extents – user1186 Oct 3 '16 at 8:54
3

Function to get bounding box or center coordinate in list given different options for country name:

def get_boundingbox_country(country, output_as='boundingbox'):
    """
    get the bounding box of a country in EPSG4326 given a country name

    Parameters
    ----------
    country : str
        name of the country in english and lowercase
    output_as : 'str
        chose from 'boundingbox' or 'center'. 
         - 'boundingbox' for [latmin, latmax, lonmin, lonmax]
         - 'center' for [latcenter, loncenter]

    Returns
    -------
    output : list
        list with coordinates as str
    """
    # create url
    url = '{0}{1}{2}'.format('http://nominatim.openstreetmap.org/search?country=',
                             country,
                             '&format=json&polygon=0')
    response = requests.get(url).json()[0]

    # parse response to list
    if output_as == 'boundingbox':
        lst = response[output_as]
        output = [float(i) for i in lst]
    if output_as == 'center':
        lst = [response.get(key) for key in ['lat','lon']]
        output = [float(i) for i in lst]
    return output

Usage:

In [42]: get_boundingbox_country(country='netherlands')
Out[42]: [11.777, 53.7253321, -70.2695876, 7.2274985]

In [43]: get_boundingbox_country(country='holland')
Out[43]: [11.777, 53.7253321, -70.2695876, 7.2274985]

In [44]: get_boundingbox_country(country='nl')
Out[44]: [11.777, 53.7253321, -70.2695876, 7.2274985]

In [45]: get_boundingbox_country(country='nl', output_as='center')
Out[45]: [52.5001698, 5.7480821]
3

Nominatim is a useful geocoding tool. I wrote a simple script a while ago to return lat, long, and name for a given search term - you could amend it to return the bounding box instead.

import argparse
import json
import sys
import urllib


def main(args):
    url = u'http://nominatim.openstreetmap.org/search?'
    query = []
    if args['street']:
        query.append('street={}'.format(args['street']))
    if args['city']:
        query.append('city={}'.format(args['city']))
    if args['county']:
        query.append('county={}'.format(args['county']))
    if args['country']:
        query.append('country={}'.format(args['country']))
    if args['postcode']:
        query.append('postalcode={}'.format(args['postcode']))
    if args['format']:
        query.append('format={}'.format(args['format']))
    else:
        query.append('format=json')
    if not args['street'] and not args['city'] and not args['county'] \
        and not args['country'] and not args['postcode']:
        query.append('q={}'.format(args['query']))

    url += '&'.join(query)

    results = urllib.urlopen(url).read()
    for result in json.loads(results):
        print '{0}, {1}: {2}'.format(
            result['lat'],
            result['lon'],
            result['display_name'].encode('utf-8')
        )


def parse_args():
    parser = argparse.ArgumentParser(description='Geocoding utility')
    parser.add_argument('-s', '--street', nargs='+', help='House number and \
                        street name', metavar=('NUMBER', 'NAME'))
    parser.add_argument('-i', '--city', help='City name')
    parser.add_argument('-c', '--county', help='County name')
    parser.add_argument('-r', '--country', help='Country name')
    parser.add_argument('-p', '--postcode', help='Postcode')
    parser.add_argument('-f', '--format', default='json', help='Format \
                        [html|xml|json|jsonv2]')
    parser.add_argument('query', help='Query string to search for. Maybe used\
                        instead of street, city, county, country, and \
                        postcode', nargs='?')
    return vars(parser.parse_args())

if __name__ == '__main__':
    main(parse_args())
2

Based on @jon_two answer, I will simplify it more. You can make a simple HTTP request as below and get simple Geo data including the Bounding box in the response as JSON :

link:
http://nominatim.openstreetmap.org/search?country=germany&format=json&polygon=0

  • fyi - nominatim service includes overseas territories – Mattijn Nov 23 '17 at 15:36
1

You can download any of the available country border datasets online and use any of the geospatial libraries in Python (fiona, ogr, geopandas, etc.).

For example, download a country border dataset from http://thematicmapping.org/downloads/world_borders.php

wget http://thematicmapping.org/downloads/TM_WORLD_BORDERS-0.3.zip

After which you can do

import geopandas as gpd

country_df = gpd.read_file("TM_WORLD_BORDERS-0.3.shp", vfs="zip://TM_WORLD_BORDERS-0.3.zip/")
def get_country_window(country):
    return country_df[country_df["NAME"].str.lower() == country.lower()].geometry.values[0].bounds

get_country_window('United states')

The above returns (-179.14199799999994, 18.923882000000106, 179.77746600000012, 71.36581400000006).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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