test do_stdref, too
[osm-ro-tools.git] / OsmUtils.py
blobfdae7d562da0123e9683c71854b082c506a7fa6f
1 #-*- coding: utf-8 -*-
2 # vim:noet:ts=4:sw=4:
4 # Various OSM-related utilities useful for mass manipulation
6 __version__ = '0.1'
8 from OsmApi import OsmApi
9 from math import cos, radians
10 import re
11 import os
12 from copy import deepcopy
15 class OsmApiExt(OsmApi):
17 def __init__(self,
18 passwordfile=None,
19 username=None,
20 password=None,
21 appname='OsmUtils' + __version__,
22 comment=u'updated with OsmUtils'
25 if username or password:
26 raise NotImplementedError(
27 'Username+password authentication not implemented')
29 if not passwordfile:
30 homedir = os.environ['HOME']
31 self._pwfile = homedir + '/.config/osm-utils/osm-auth'
32 else:
33 self._pwfile = passwordfile
35 api = OsmApi(passwordfile=self._pwfile, appid=appname,
36 changesetauto=True,
37 changesetautotags={u'comment': comment})
38 self._api = api
39 self._map = None
41 def __del__(self):
42 del self._api
43 del self._map
44 return None
46 def MapAroundPoint(self, lon=None, lat=None, bbox_km=10):
47 """
48 Given the latitude 'lat' and longitude 'lon', get from the API the map
49 around that point within a bbox_km area
51 Returns a list of dict {type: node|way|relation, data: {}}. """
53 if not lon and self._lon:
54 lon = self._lon
55 else:
56 raise ValueError
58 if not lat and self._lat:
59 lat = self._lat
60 else:
61 raise ValueError
63 # one degree latitude is approximately 111km
64 # and we want to know what's half of bbox_km in lat degrees
65 delta_lat = bbox_km / 222.0
67 lat = float(lat)
68 lon = float(lon)
69 # one degree longitude is a cos(lat) * 111
70 # and we want to know what's half of bbox_km in lon degrees
71 delta_lon = cos(radians(lat)) * delta_lat
73 lat_b = lat - delta_lat
74 lat_t = lat + delta_lat
76 lon_l = lon - delta_lon
77 lon_r = lon + delta_lon
79 self._map = self._api.Map(lon_l, lat_b, lon_r, lat_t)
80 return self._map
82 def mapFocus(self, lat, lon):
83 self._lat = lat
84 self._lon = lon
86 def getApiMap(self, lat=None, lon=None, bbox=None, amap=None):
88 if not amap:
89 if not lat:
90 if not self._lat:
91 raise NameError('lat not defined')
92 else:
93 lat = self._lat
94 if not lon:
95 if not self._lon:
96 raise NameError('lon not defined')
97 else:
98 lon = self._lon
99 self.mapFocus(lat, lon)
100 if not bbox:
101 amap = self.MapAroundPoint()
102 else:
103 amap = self.MapAroundPoint(bbox_km=bbox)
104 else:
105 self._map = deepcopy(amap)
107 return self._map
109 @staticmethod
110 def grepElementsInMap(amap, tag, pattern, etype=u'way', flags=re.I + re.U):
112 # obtain all elements of type etype
113 elems = [x[u'data'] for x in amap if (x[u'type'] == etype)]
115 regex = re.compile(pattern, flags)
116 result = []
117 for x in elems:
118 try:
119 if regex.match(x[u'tag'][tag]):
120 result.append(x)
121 except KeyError:
122 pass
124 if not result:
125 return []
126 else:
127 return result