seisobs-webapp/scripts/mkGeolocationTable.py

62 lines
1.8 KiB
Python
Executable File

#! /usr/bin/env python
# -*- coding: utf-8 -*-
# $Id$
'''
Script to lookup city names of events with Nominatim service
The input should be an valid quakeML file passed to stdin.
The output will will be a javascript structure to be included in the
SeisObs map service.
the script should be updated regulary keep the total number of all
AJAX calls to the Nominatim service small
'''
# imports
try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
from sys import stdin
import urllib2 as URL
import json as JSON
# constants
namespaces = {'sc3': 'http://geofon.gfz-potsdam.de/ns/seiscomp3-schema/0.7',
'qml': 'http://quakeml.org/xmlns/bed/1.2'}
# initialise variables
geolocationTable = {};
# parse event.xml
DOM = ET.parse(stdin).getroot()
#DOM = ET.parse('../www/event.xml').getroot()
# iterate over all events
for event in DOM.iterfind('qml:eventParameters/qml:event', namespaces):
publicID = event.attrib['publicID'].split('/')[2]
lat = event.find('./qml:origin/qml:latitude/qml:value', namespaces).text
lng = event.find('./qml:origin/qml:longitude/qml:value', namespaces).text
url = 'https://open.mapquestapi.com/nominatim/v1/reverse.php?lat={0}&lon={1}&zoom=10&format=json'.format(lat, lng)
# send and evaluate nominatim request
response = URL.urlopen(url)
if ( response.msg == 'OK' ):
data = JSON.loads(response.read())
try:
city = data['address']['city']
country = data['address']['country']
countryCode = data['address']['country_code'].upper()
value = city
if ( countryCode != 'DE' ):
value = '{0} ({1})'.format(value, countryCode)
geolocationTable[publicID] = value
except:
print 'Could not etract city for event {0}'.format(publicID)
else:
print 'Request {0} failed'.format(url)
# dump json
print 'var geolocationTable = '+JSON.dumps(geolocationTable)