Last active
October 31, 2022 22:31
-
-
Save borsna/59e32f6d8a4a7ce4481466430a7e9031 to your computer and use it in GitHub Desktop.
Get country code by geopoint
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
shapely=1.8.1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi @alessiabardi
countries.geojson
is published here: https://datahub.io/core/geo-countries (direct link: https://datahub.io/core/geo-countries/r/countries.geojson)