Instantly share code, notes, and snippets.

Embed
What would you like to do?
Function to retrieve region name based on administrative level and coordinates.
import os, json, time
import requests
from urllib.request import Request, urlopen
from termcolor import colored
debug_msg = True
def get_region_name(lat,lng,region_type):
def adm_parser(regtype):
tr = {
'adm0': 'country',
'adm1': 'administrative_area_level_1',
'adm2': 'administrative_area_level_2',
'adm3': 'administrative_area_level_3',
'adm4': 'administrative_area_level_4',
'city': 'locality'
}
return tr[regtype]
try:
urlApi = "https://maps.googleapis.com/maps/api/geocode/json?/"
latlng= str(lat) +','+str(lng)
payload = {'latlng': latlng}
web = requests.get(urlApi, params=payload)
data = web.text
js = json.loads(data)
if 'status' not in js:
if debug_msg: print (time.strftime("%Y-%m-%d %H:%M:%S"), colored('Failure getting point location. Status not in JS','red'))
return False
elif js['status'] == 'ZERO_RESULTS':
if debug_msg: print (time.strftime("%Y-%m-%d %H:%M:%S"), colored('Failure getting point location. Zero results','red'))
return False
elif js['status'] == 'OVER_QUERY_LIMIT':
if debug_msg: print (time.strftime("%Y-%m-%d %H:%M:%S"), colored('Failure getting point location. Over query','red'))
if debug_msg: print (time.strftime("%Y-%m-%d %H:%M:%S"), 'Start waiting...')
time.sleep(5*60)
return False
else:
for result in js["results"]:
if 'political' in result['types'] and adm_parser(region_type) in result['types']:
for component in result['address_components']:
if adm_parser(region_type) in component['types']:
return component['long_name']
if debug_msg: print (time.strftime("%Y-%m-%d %H:%M:%S"), colored('No '+region_type+' in result','yellow'))
return False
except Exception as e:
if debug_msg: print (time.strftime("%Y-%m-%d %H:%M:%S"), colored('Error general in get_point_adress','red'), e)
return False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment