Statistics
| Revision:

gvsig-scripting / org.gvsig.scripting / trunk / org.gvsig.scripting / org.gvsig.scripting.app / org.gvsig.scripting.app.mainplugin / src / main / resources-plugin / scripting / lib / geopy / geocoders / openmapquest.py @ 545

History | View | Annotate | Download (3.96 KB)

1
"""
2
:class:`.OpenMapQuest` geocoder.
3
"""
4

    
5
from geopy.compat import urlencode
6
from geopy.geocoders.base import (
7
    Geocoder,
8
    DEFAULT_FORMAT_STRING,
9
    DEFAULT_TIMEOUT,
10
    DEFAULT_SCHEME
11
)
12
from geopy.location import Location
13
from geopy.util import logger
14

    
15

    
16
__all__ = ("OpenMapQuest", )
17

    
18

    
19
class OpenMapQuest(Geocoder): # pylint: disable=W0223
20
    """
21
    Geocoder using MapQuest Open Platform Web Services. Documentation at:
22
        http://developer.mapquest.com/web/products/open/geocoding-service
23
    """
24

    
25
    def __init__(
26
            self,
27
            api_key=None,
28
            format_string=DEFAULT_FORMAT_STRING,
29
            scheme=DEFAULT_SCHEME,
30
            timeout=DEFAULT_TIMEOUT,
31
            proxies=None,
32
        ):  # pylint: disable=R0913
33
        """
34
        Initialize an Open MapQuest geocoder with location-specific
35
        address information. No API Key is needed by the Nominatim based
36
        platform.
37

38
        :param string format_string: String containing '%s' where
39
            the string to geocode should be interpolated before querying
40
            the geocoder. For example: '%s, Mountain View, CA'. The default
41
            is just '%s'.
42

43
        :param string scheme: Use 'https' or 'http' as the API URL's scheme.
44
            Default is https. Note that SSL connections' certificates are not
45
            verified.
46

47
            .. versionadded:: 0.97
48

49
        :param int timeout: Time, in seconds, to wait for the geocoding service
50
            to respond before raising a :class:`geopy.exc.GeocoderTimedOut`
51
            exception.
52

53
            .. versionadded:: 0.97
54

55
        :param dict proxies: If specified, routes this geocoder's requests
56
            through the specified proxy. E.g., {"https": "192.0.2.0"}. For
57
            more information, see documentation on
58
            :class:`urllib2.ProxyHandler`.
59

60
            .. versionadded:: 0.96
61
        """
62
        super(OpenMapQuest, self).__init__(
63
            format_string, scheme, timeout, proxies
64
        )
65
        self.api_key = api_key or ''
66
        self.api = "%s://open.mapquestapi.com/nominatim/v1/search" \
67
                    "?format=json" % self.scheme
68

    
69
    def geocode(self, query, exactly_one=True, timeout=None): # pylint: disable=W0221
70
        """
71
        Geocode a location query.
72

73
        :param string query: The address or query you wish to geocode.
74

75
        :param bool exactly_one: Return one result or a list of results, if
76
            available.
77

78
        :param int timeout: Time, in seconds, to wait for the geocoding service
79
            to respond before raising a :class:`geopy.exc.GeocoderTimedOut`
80
            exception. Set this only if you wish to override, on this call
81
            only, the value set during the geocoder's initialization.
82

83
            .. versionadded:: 0.97
84
        """
85
        params = {
86
            'q': self.format_string % query
87
        }
88
        if exactly_one:
89
            params['maxResults'] = 1
90
        url = "&".join((self.api, urlencode(params)))
91

    
92
        logger.debug("%s.geocode: %s", self.__class__.__name__, url)
93
        return self._parse_json(
94
            self._call_geocoder(url, timeout=timeout),
95
            exactly_one
96
        )
97

    
98
    @classmethod
99
    def _parse_json(cls, resources, exactly_one=True):
100
        """
101
        Parse display name, latitude, and longitude from an JSON response.
102
        """
103
        if not len(resources): # pragma: no cover
104
            return None
105
        if exactly_one:
106
            return cls.parse_resource(resources[0])
107
        else:
108
            return [cls.parse_resource(resource) for resource in resources]
109

    
110
    @classmethod
111
    def parse_resource(cls, resource):
112
        """
113
        Return location and coordinates tuple from dict.
114
        """
115
        location = resource['display_name']
116

    
117
        latitude = resource['lat'] or None
118
        longitude = resource['lon'] or None
119
        if latitude and longitude:
120
            latitude = float(latitude)
121
            longitude = float(longitude)
122

    
123
        return Location(location, (latitude, longitude), resource)