source: genesis/tools/rdnap.py@ 9843

Last change on this file since 9843 was 9822, checked in by rick, 13 years ago

Make the rdnap parser a bit more robust

File size: 1.8 KB
Line 
1#
2# REMEMBER
3# latitude : phi
4# longitude : lam
5#
6import os
7import yaml
8import urllib
9
10try:
11 CACHE_FILE = os.environ['RD2ETRS_CACHE']
12except KeyError:
13 CACHE_FILE = os.path.join(os.environ['HOME'],'.rd2etrs.yaml')
14coordinates = None
15
16def get_yaml(gfile):
17 """ Get configuration yaml for 'item'"""
18 f = open(gfile, 'r')
19 datadump = yaml.load(f)
20 return datadump
21
22def write_yaml(gfile, datadump):
23 """ Write configuration yaml for 'item'"""
24 try:
25 f = open(gfile, 'w')
26 f.write(yaml.dump(datadump, default_flow_style=False))
27 f.close()
28 except IOError:
29 pass
30
31def etrs2rd(lam, phi):
32 """ Convert etrs to rd """
33
34 item['lam'] = lam
35 item['phi'] = phi
36 item['func'] = 'etrs2rd'
37 url = 'http://vanderzwet.net/rdnap/%(func)s/%(xrd)s/%(yrd)s/0/' % item
38
39 f = urllib.urlopen(url)
40 raw = f.read()
41
42 rdnap_x,rdnap_y,rdnap_h = raw.split('/')
43 return (rdnap_x, rdnap_y)
44
45
46
47def rd2etrs(xrd, yrd, hnap=0.0):
48 """
49 Convert rd to etrs
50 JavaScript Version: https://rdinfo.kadaster.nl/rd/transformator.html
51 """
52 # Get cache is exists
53 global coordinates
54 if coordinates == None:
55 try:
56 coordinates = get_yaml(CACHE_FILE)
57 except (IOError,AttributeError):
58 coordinates = dict()
59 pass
60
61 # Check if item in cache
62 xrd = float(str(xrd))
63 yrd = float(str(yrd))
64 if coordinates.has_key((xrd, yrd)):
65 return coordinates[(xrd, yrd)]
66
67 # Get new coordinate
68 item = dict()
69 item['xrd'] = xrd
70 item['yrd'] = yrd
71 item['hnap'] = hnap
72 item['func'] = 'rd2etrs'
73 url = 'http://vanderzwet.net/rdnap/%(func)s/%(xrd)s/%(yrd)s/%(hnap)s/' % item
74 print "### Not in Cache, Fetching coordinate %s, %s from %s" % (xrd, yrd, url)
75 f = urllib.urlopen(url)
76 raw = f.read()
77
78 # Coordinates returned in 'odd' order
79 phi,lam,h = raw.split('/')
80 coordinates[(xrd, yrd)] = (lam, phi)
81 write_yaml(CACHE_FILE, coordinates)
82 return (lam, phi)
Note: See TracBrowser for help on using the repository browser.