I'm writing a python script that generates random addresses in Canada. To do this, I have to generate random tuples (longitude,latitude) that are within Canadian borders (not in the ocean). I figured that I can approximate the borders with small rectangles (just like in calculus). Which does the job, but it is not optimal/accurate.
I couldn't find any academic paper/discussion on the web, maybe my searches did not contain the right keywords. Can you help me find the right resources or even answer this question? The programming part is fine, I just need the math!
Thank you
You are talking about reverse geocoding. The easiest way to do this is to make use of the google maps geocoding API.
You can do this without registering, but you are limited to like 4-5 calls per day. You can register for free for a relatively high number of calls (20-25k last I checked) and if you exceed that you have to pay.
import requests
import json
def getplace(lat, lon):
url = "http://maps.googleapis.com/maps/api/geocode/json?"
url += "latlng=%s,%s&sensor=false" % (lat, lon)
data = {'key': 'your-api-key-goes-here'} # If using your free 5 calls, include no data and just doa get request on the url
v = requests.post(url=url, data=data)
j = json.loads(v.text)
components = j['results'][0]['address_components']
country = town = None
for c in components:
if "country" in c['types']:
country = c['long_name']
if "locality" in c['types']:
town = c['long_name']
return town, country
print(getplace(45.425533, -75.69248))
print(getplace(45.525533, -77.69248))
The above outputs: ('Ottawa', 'Canada') ("Barry's Bay", 'Canada')
You can print out the raw response print(v.text
to see the data object and find the fields you actually care about