~hsiung0911/sahana-eden/test

« back to all changes in this revision

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

  • Committer: eliao
  • Date: 2010-08-01 09:56:45 UTC
  • Revision ID: eliao@ibm-l3bw307-20100801095645-gsq9wcmjan0o0tby
This is my change

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
import xml.dom.minidom
 
2
from geopy import util
 
3
from geopy import Point, Location
 
4
from urllib import urlencode
 
5
from urllib2 import urlopen, HTTPError
 
6
from geopy.geocoders.base import Geocoder
 
7
 
 
8
 
 
9
class Yahoo(Geocoder):
 
10
 
 
11
    BASE_URL = "http://api.local.yahoo.com/MapsService/V1/geocode?%s"
 
12
 
 
13
    def __init__(self, app_id, format_string='%s', output_format='xml'):
 
14
        self.app_id = app_id
 
15
        self.format_string = format_string
 
16
        self.output_format = output_format.lower()
 
17
 
 
18
    def geocode(self, string):
 
19
        params = {'location': self.format_string % string,
 
20
                  'output': self.output_format,
 
21
                  'appid': self.app_id
 
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)
 
29
 
 
30
        parse = getattr(self, 'parse_' + self.output_format)
 
31
        return parse(page)
 
32
 
 
33
    def parse_xml(self, page):
 
34
        if not isinstance(page, basestring):
 
35
            page = util.decode_page(page)
 
36
 
 
37
        doc = xml.dom.minidom.parseString(page)
 
38
        results = doc.getElementsByTagName('Result')
 
39
 
 
40
        def parse_result(result):
 
41
            strip = ", \n"
 
42
            address = util.get_first_text(result, 'Address', strip)
 
43
            city = util.get_first_text(result, 'City', strip)
 
44
            state = util.get_first_text(result, 'State', strip)
 
45
            zip = util.get_first_text(result, 'Zip', strip)
 
46
            country = util.get_first_text(result, 'Country', strip)
 
47
            city_state = util.join_filter(", ", [city, state])
 
48
            place = util.join_filter(" ", [city_state, zip])
 
49
            location = util.join_filter(", ", [address, place, country])
 
50
            latitude = util.get_first_text(result, 'Latitude') or None
 
51
            longitude = util.get_first_text(result, 'Longitude') or None
 
52
            if latitude and longitude:
 
53
                point = Point(latitude, longitude)
 
54
            else:
 
55
                point = Non
 
56
            return Location(location, point, {
 
57
                'Address': address,
 
58
                'City': city,
 
59
                'State': state,
 
60
                'Zip': zip,
 
61
                'Country': country
 
62
            })
 
63
 
 
64
        return [parse_result(result) for result in results]