コード例 #1
0
ファイル: maps.py プロジェクト: team999/flightlog
    def __unicode__(self):
        """Produces a static map image url.

        Don't forget to set the map option 'size' (as an instance
        of maps.Size). Or alternatively you can append it to the
        resulting string (e.g. '&size=400x400').

        """
        opts = self['arg'].get('opts', {})
        params = []
        for p in ['center', 'zoom', 'size', 'format', 'language']:
            if p in opts:
                params.append((p, unicode(opts[p])))
        if 'mapTypeId' in opts:
            params.append(('maptype', unicode(opts['mapTypeId'])))
        if 'visible' in opts:
            params.append(('visible', '|'.join([unicode(v)
                                                for v in opts['visible']])))
        if 'mkr' in self:
            params.append(('markers', [unicode(m) for m in self['mkr']]))
        if 'pln' in self:
            params.append(('path', [unicode(p) for p in self['pln']]))
        if 'pgn' in self:
            params.append(('path', [q for p in self['pgn']
                                    for q in unicode(p).split('&path=')]))
        params.append(('sensor', 'true' if opts.get('sensor') else 'false'))
        return '%s?%s' % (STATIC_URL, urlencode(params, doseq=True))
コード例 #2
0
    def geocode(self, request, callback=None):
        """Geocode a request.

        Unlike the javascript API, this method is blocking. So, even
        though a callback function is supported, the method will also
        return the results and status directly.

        """
        # Handle any unicode in the request.
        if 'address' in request:
            request['address'] = smart_str(request['address'],
                                           strings_only=True).lower()
        # Add the sensor parameter if needed.
        if 'sensor' in request:
            if request['sensor'] != 'false':
                request['sensor'] = 'true' if request['sensor'] else 'false'
        else:
            request['sensor'] = 'false'
        cache_key = urlencode(request)
        url = '%s/json?%s' % (GEOCODE_URL, cache_key)
        # Try up to 30 times if over query limit.
        for _ in xrange(30):
            # Check if result is already cached.
            data = cache.get(cache_key)
            if data is None:
                if (max(0,
                        time.time() - self.__class__._last) <
                        self.__class__._sleep):
                    # Wait a bit so that we don't make requests too fast.
                    time.sleep(
                        max(
                            0, self.__class__._sleep + self.__class__._last -
                            time.time()))
                data = urllib.urlopen(url).read()
                self.__class__._last = time.time()
            response = loads(data)
            status = response['status']

            if status == 'OVER_QUERY_LIMIT':
                # Over limit, increase delay a bit.
                if self.__class__._block:
                    break
                self.__class__._sleep += .1
            else:
                # Save results to cache.
                cache.set(cache_key, data)
                if status == 'OK':
                    # Successful query, clear block if there is one.
                    if self.__class__._block:
                        self.__class__._block = False
                        self.__class__._sleep = 0
                    results = _parseGeocoderResult(response['results'])
                    if callback:
                        callback(results, status)
                    return results, status
                else:
                    return None, status
        self.__class__._block = True
        raise SystemError('Geocoding has failed too many times. '
                          'You might have exceeded your daily limit.')
コード例 #3
0
    def __unicode__(self):
        """Produces a static map image url.

        Don't forget to set the map option 'size' (as an instance
        of maps.Size). Or alternatively you can append it to the
        resulting string (e.g. '&size=400x400').

        """
        opts = self['arg'].get('opts', {})
        params = []
        for p in ['center', 'zoom', 'size', 'format', 'language']:
            if p in opts:
                params.append((p, unicode(opts[p])))
        if 'mapTypeId' in opts:
            params.append(('maptype', unicode(opts['mapTypeId'])))
        if 'visible' in opts:
            params.append(
                ('visible', '|'.join([unicode(v) for v in opts['visible']])))
        if 'mkr' in self:
            params.append(('markers', [unicode(m) for m in self['mkr']]))
        if 'pln' in self:
            params.append(('path', [unicode(p) for p in self['pln']]))
        if 'pgn' in self:
            params.append(
                ('path',
                 [q for p in self['pgn'] for q in unicode(p).split('&path=')]))
        params.append(('sensor', 'true' if opts.get('sensor') else 'false'))
        return '%s?%s' % (STATIC_URL, urlencode(params, doseq=True))
コード例 #4
0
    def __unicode__(self):
        """Produces a static map image url.

        Don't forget to set the map option 'size' (as an instance
        of maps.Size). Or alternatively you can append it to the
        resulting string (e.g. '&size=400x400').

        """
        opts = self["arg"].get("opts", {})
        params = []
        for p in ["center", "zoom", "size", "format", "language"]:
            if p in opts:
                params.append((p, unicode(opts[p])))
        if "mapTypeId" in opts:
            params.append(("maptype", unicode(opts["mapTypeId"])))
        if "visible" in opts:
            params.append(("visible", "|".join([unicode(v) for v in opts["visible"]])))
        if "mkr" in self:
            params.append(("markers", [unicode(m) for m in self["mkr"]]))
        if "pln" in self:
            params.append(("path", [unicode(p) for p in self["pln"]]))
        if "pgn" in self:
            params.append(("path", [q for p in self["pgn"] for q in unicode(p).split("&path=")]))
        params.append(("sensor", "true" if opts.get("sensor") else "false"))
        return "%s?%s" % (STATIC_URL, urlencode(params, doseq=True))
コード例 #5
0
ファイル: maps.py プロジェクト: machtfit/django-gmapi
    def geocode(self, request, callback=None):
        """Geocode a request.

        Unlike the javascript API, this method is blocking. So, even
        though a callback function is supported, the method will also
        return the results and status directly.

        """
        # Handle any unicode in the request.
        if "address" in request:
            request["address"] = smart_str(request["address"], strings_only=True).lower()
        # Add the sensor parameter if needed.
        if "sensor" in request:
            if request["sensor"] != "false":
                request["sensor"] = "true" if request["sensor"] else "false"
        else:
            request["sensor"] = "false"

        # add api key if not already present
        if API_KEY is not None and "key" not in request:
            request["key"] = API_KEY

        cache_key = urlencode(request)
        url = "%s/json?%s" % (GEOCODE_URL, cache_key)
        # Try up to 30 times if over query limit.
        for _ in xrange(30):
            # Check if result is already cached.
            data = cache.get(cache_key)
            if data is None:
                if max(0, time.time() - self.__class__._last) < self.__class__._sleep:
                    # Wait a bit so that we don't make requests too fast.
                    time.sleep(max(0, self.__class__._sleep + self.__class__._last - time.time()))
                data = urllib.urlopen(url).read()
                self.__class__._last = time.time()
            response = loads(data)
            status = response["status"]

            if status == "OVER_QUERY_LIMIT":
                # Over limit, increase delay a bit.
                if self.__class__._block:
                    break
                self.__class__._sleep += 0.1
            else:
                # Save results to cache.
                cache.set(cache_key, data)
                if status == "OK":
                    # Successful query, clear block if there is one.
                    if self.__class__._block:
                        self.__class__._block = False
                        self.__class__._sleep = 0
                    results = _parseGeocoderResult(response["results"])
                    if callback:
                        callback(results, status)
                    return results, status
                else:
                    return None, status
        self.__class__._block = True
        raise SystemError("Geocoding has failed too many times. " "You might have exceeded your daily limit.")
コード例 #6
0
ファイル: maps.py プロジェクト: team999/flightlog
    def geocode(self, request, callback=None):
        """Geocode a request.

        Unlike the javascript API, this method is blocking. So, even
        though a callback function is supported, the method will also
        return the results and status directly.

        """
        # Handle any unicode in the request.
        if 'address' in request:
            request['address'] = smart_str(request['address'],
                                           strings_only=True).lower()
        # Add the sensor parameter if needed.
        if 'sensor' in request:
            if request['sensor'] != 'false':
                request['sensor'] = 'true' if request['sensor'] else 'false'
        else:
            request['sensor'] = 'false'
        cache_key = urlencode(request)
        url = '%s/json?%s' % (GEOCODE_URL, cache_key)
        # Try up to 30 times if over query limit.
        for _ in xrange(30):
            # Check if result is already cached.
            data = cache.get(cache_key)
            if data is None:
                if (max(0, time.time() - self.__class__._last) <
                    self.__class__._sleep):
                    # Wait a bit so that we don't make requests too fast.
                    time.sleep(max(0, self.__class__._sleep +
                                      self.__class__._last - time.time()))
                data = urllib.urlopen(url).read()
                self.__class__._last = time.time()
            response = loads(data)
            status = response['status']

            if status == 'OVER_QUERY_LIMIT':
                # Over limit, increase delay a bit.
                if self.__class__._block:
                    break
                self.__class__._sleep += .1
            else:
                # Save results to cache.
                cache.set(cache_key, data)
                if status == 'OK':
                    # Successful query, clear block if there is one.
                    if self.__class__._block:
                        self.__class__._block = False
                        self.__class__._sleep = 0
                    results = _parseGeocoderResult(response['results'])
                    if callback:
                        callback(results, status)
                    return results, status
                else:
                    return None, status
        self.__class__._block = True
        raise SystemError('Geocoding has failed too many times. '
                          'You might have exceeded your daily limit.')
コード例 #7
0
    def elevation(self, request, callback=None):
        """Gets the elevation of a request.

        Unlike the javascript API, this method is blocking. So, even
        though a callback function is supported, the method will also
        return the results and status directly.

        """
        # Add the sensor parameter if needed.
        if "sensor" in request:
            if request["sensor"] != "false":
                request["sensor"] = "true" if request["sensor"] else "false"
        else:
            request["sensor"] = "false"
        encoded_request = urlencode(request)
        url = "%s/json?%s" % (ELEVATION_URL, encoded_request)
        cache_key = url
        # Try up to 30 times if over query limit.
        for _ in xrange(30):
            # Check if result is already cached.
            data = cache.get(cache_key)
            if data is None:
                if max(0, time.time() - self.__class__._last) < self.__class__._sleep:
                    # Wait a bit so that we don't make requests too fast.
                    time.sleep(max(0, self.__class__._sleep + self.__class__._last - time.time()))
                data = urllib.urlopen(url).read()
                self.__class__._last = time.time()
            response = json.loads(data)
            status = response["status"]

            if status == "OVER_QUERY_LIMIT":
                # Over limit, increase delay a bit.
                if self.__class__._block:
                    break
                self.__class__._sleep += 0.1
            else:
                # Save results to cache.
                cache.set(cache_key, data)
                if status == "OK":
                    # Successful query, clear block if there is one.
                    if self.__class__._block:
                        self.__class__._block = False
                        self.__class__._sleep = 0
                    results = _parseLatLonResult(response["results"])
                    if callback:
                        callback(results, status)
                    return results, status
                else:
                    return None, status
        self.__class__._block = True
        raise SystemError("The elevation API has failed too many times. " "You might have exceeded your daily limit.")