Skip to content

Instantly share code, notes, and snippets.

@borsna
Last active October 31, 2022 22:31
Show Gist options
  • Save borsna/59e32f6d8a4a7ce4481466430a7e9031 to your computer and use it in GitHub Desktop.
Save borsna/59e32f6d8a4a7ce4481466430a7e9031 to your computer and use it in GitHub Desktop.
Get country code by geopoint
import json
import urllib.request
import os.path
from shapely.geometry import shape, Point
# download countries.geojson if needed
if not os.path.exists('countries.geojson'):
urllib.request.urlretrieve("https://datahub.io/core/geo-countries/r/countries.geojson", "countries.geojson")
# load GeoJSON containing country polygons
# Get file from: https://datahub.io/core/geo-countries
with open('countries.geojson') as f:
countries = json.load(f)
# dict to store key-value for country code and polygon
countries_dict = {}
# read countries polygons to a dict
for feature in countries['features']:
polygon = shape(feature['geometry'])
isoCode = feature["properties"]["ISO_A3"]
countries_dict[isoCode] = polygon
def get_country_code(point):
for countryCode, polygon in countries_dict.items():
if polygon.contains(point):
return countryCode
break
return None
# example looking for cooridnates for each row in geopoints.txt
cooridnates_file = open('geopoints.txt', 'r')
lines = cooridnates_file.readlines()
for line in lines:
parts = line.split() #split each coorinates on space
point = Point(float(parts[0]), float(parts[1]))
countryCode = get_country_code(point)
print('{} found in : {}'.format(point, countryCode))
148.04 -32.46
67.78171 34.36084
13.24543 15.70716
-99.73082 52.93423
13.41667 52.5
4.36667 50.86667
2.33333 48.8
18.05 59.28333
12.56667 55.66667
10.7 59.95
@alessiabardi
Copy link

Hi @borsna , where can I download the countries.geojson input file?

@borsna
Copy link
Author

borsna commented May 3, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment