import urllib.request, urllib.parse
import json, ssl
# API endpoint with placeholder for your Geoapify API key
serviceurl = 'https://a...content-available-to-author-only...y.com/v2/places?q={}&format=json&apiKey=YOUR_API_KEY'
# Ignore SSL certificate errors (not recommended for production)
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
while True:
address = input('Enter location: ')
if len(address) < 1: break
address = address.strip()
parms = dict()
parms['q'] = address
url
= serviceurl
.format
(urllib
.parse
.urlencode(parms
))
print('Retrieving', url)
uh = urllib.request.urlopen(url, context=ctx)
data = uh.read().decode()
print('Retrieved', len(data), 'characters', data[:20].replace('\n', ' '))
try:
js = json.loads(data)
except json.JSONDecodeError:
print('==== JSON decoding error ===')
print('Failed to parse response data as JSON.')
continue
if 'features' not in js or len(js['features']) == 0:
print('==== Object not found or invalid response format ===')
print(data[:100]) # Truncate output for brevity
continue
# Extract location data with error handling
location_data = js['features'][0]['properties']
latitude = location_data.get('lat')
longitude = location_data.get('lon')
plus_code = location_data.get('plus_code')
formatted_address = location_data.get('formatted')
# Check for data availability
if not all([latitude, longitude, plus_code, formatted_address]):
print('==== Missing data in response ===')
print('Required data may be unavailable for the entered location.')
continue
# Print results
print('Latitude:', latitude)
print('Longitude:', longitude)
print('Plus code:', plus_code)
print('Formatted address:', formatted_address)
# Example usage (assuming you have a function to process this data)
# process_location_data(latitude, longitude, plus_code, formatted_address)