Skip to content
This repository has been archived by the owner on Dec 25, 2024. It is now read-only.

TOOLS: Fix loadGeoPossibilities #608

Merged
merged 2 commits into from
Jan 4, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,4 @@ opacclient/opacapp/src/main/assets/bibs/*.json
opacclient/opacapp/src/main/assets/last_library_config_update.txt
opacclient/opacapp/src/main/resources/sentry.properties

tools/googlemaps_api_key.txt
62 changes: 41 additions & 21 deletions tools/add_library.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from bs4 import BeautifulSoup

LIBDIR = 'opacclient/opacapp/src/main/assets/bibs/'
API_KEY_FILE = 'googlemaps_api_key.txt'
TYPES = [
'NONE', 'BOOK', 'CD', 'CD_SOFTWARE', 'CD_MUSIC', 'DVD', 'MOVIE', 'AUDIOBOOK', 'PACKAGE',
'GAME_CONSOLE', 'EBOOK', 'SCORE_MUSIC', 'PACKAGE_BOOKS', 'UNKNOWN', 'NEWSPAPER',
Expand All @@ -33,28 +34,41 @@ def getInput(required=False, default=None):
return inp


def loadGeoPossibilities(data):
def loadGeoPossibilities(data, api_key=None):
possibilities = []

for address in ('%s, %s, %s' % (data['title'], data['city'], data['state']),
'%s, %s, %s' % ('Bibliothek', data['city'], data['state']),
data['city']):
uri = 'https://maps.googleapis.com/maps/api/geocode/json?' + \
urllib.parse.urlencode({'address': address, 'sensor': 'true'})
jsoncontent = urllib.request.urlopen(uri).read().decode()
geocode = json.loads(jsoncontent)

if geocode['status'] != 'OK':
print("ERROR!")

for res in geocode['results']:
possibilities.append(
(
", ".join([a["long_name"] for a in res['address_components']]),
[float(res['geometry']['location']['lat']), float(
res['geometry']['location']['lng'])]
if api_key:
for address in ('%s, %s, %s' % (data['title'], data['city'], data['state']),
'%s, %s, %s' % ('Bibliothek', data['city'], data['state']),
data['city']):
uri = f'https://maps.googleapis.com/maps/api/geocode/json?key={api_key}&' + \
urllib.parse.urlencode({'address': address, 'sensor': 'true'})
jsoncontent = urllib.request.urlopen(uri).read().decode()
geocode = json.loads(jsoncontent)

if geocode['status'] != 'OK':
print("ERROR!")

for res in geocode['results']:
possibilities.append(
(
", ".join([a["long_name"] for a in res['address_components']]),
[float(res['geometry']['location']['lat']), float(
res['geometry']['location']['lng'])]
)
)
)
else:
api_url = 'https://nominatim.openstreetmap.org/search'
query = 'format=json&polygon=0&addressdetails=0&limit=40'
parameters1 = urllib.parse.quote(','.join((data['title'], data['city'].partition('(')[0],
data['state'],data['country'])), safe=',')
parameters2 = urllib.parse.urlencode({'country': data['country'], 'state': data['state'],
'city': data['city'].partition('(')[0]})
for uri in (f'{api_url}/{parameters1}?{query}',
f'{api_url}?{query}&amenity=library&{parameters2}'):
jsoncontent = urllib.request.urlopen(uri).read().decode()
for p in json.loads(jsoncontent):
possibilities.append((p["display_name"], [float(p['lat']), float(p['lon'])]))

return possibilities

Expand Down Expand Up @@ -399,8 +413,14 @@ def prompt(self, data):
data['title'] = getInput(default="Stadtbibliothek")

print("Lade Geodaten...")

geo = loadGeoPossibilities(data)
try:
with open(os.path.join(os.path.dirname(__file__), API_KEY_FILE)) as f:
api_key = f.read().strip()
except:
print(f'Keine Google Maps API key Datei ({API_KEY_FILE}) gefunden, verwende OSM Nominatim.')
api_key = None

geo = loadGeoPossibilities(data, api_key)
for k, g in enumerate(geo):
print("[%d] %s" % (k + 1, g[0]))

Expand Down