~tim-clicks/sahana-eden/minor

« back to all changes in this revision

Viewing changes to modules/geopy/geocoders/osm.py

  • Committer: Fran Boon
  • Date: 2010-02-19 01:03:42 UTC
  • Revision ID: flavour@partyvibe.com-20100219010342-gkgpxt681ikz6xd8
Include geopy, amend to look for simplejson in gluon not django, add OSM geocoder from tcarobruce

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
import simplejson
 
2
from urllib import urlencode
 
3
from urllib2 import urlopen, HTTPError
 
4
from geopy import util
 
5
from geopy import Point, Location
 
6
from geopy.geocoders.base import Geocoder
 
7
 
 
8
 
 
9
class OSMGazetteer(Geocoder):
 
10
    
 
11
    BASE_URL = "http://nominatim.openstreetmap.org/?%s"
 
12
 
 
13
    def __init__(self, format_string='%s', viewbox=(-180,-90,180,90)):
 
14
        self.format_string = format_string
 
15
        self.viewbox = ','.join(map(str, viewbox))
 
16
        self.output_format = 'json'
 
17
 
 
18
    def geocode(self, string):
 
19
        params = {'q': self.format_string % string,
 
20
                  'format': self.output_format,
 
21
                  'viewbox': self.viewbox
 
22
                 }
 
23
        url = self.BASE_URL % urlencode(params)
 
24
        return self.geocode_url(url)
 
25
 
 
26
    def geocode_url(self, url):
 
27
        print "Fetching %s..." % url
 
28
        page = urlopen(url).read()
 
29
 
 
30
        parse = getattr(self, 'parse_' + self.output_format)
 
31
        return parse(page)
 
32
 
 
33
    def parse_json(self, page):
 
34
        attribution, sep, page = page.partition("\n")
 
35
        results = simplejson.loads(page)
 
36
        
 
37
        def parse_result(result):
 
38
            location = result.get('display_name')
 
39
            latitude = result.get('lat')
 
40
            longitude = result.get('lon')
 
41
            if latitude and longitude:
 
42
                point = Point(latitude, longitude)
 
43
            else:
 
44
                point = None
 
45
            return Location(location, point, result)
 
46
 
 
47
        return [parse_result(result) for result in results]