yandex-maps / yandex_maps /

Full commit
# coding: utf-8

Yandex.Maps API wrapper

import xml.dom.minidom
from urllib import urlencode
from yandex_maps import http


def get_map_url(api_key, longitude, latitude, zoom, width, height):
    Returns URL of static Yandex map.
    params = [
       'll=%0.7f,%0.7f' % (float(longitude), float(latitude),),
       'size=%d,%d' % (width, height,),
       'z=%d' % zoom,
       'pt=%0.7f,%0.7f' % (float(longitude), float(latitude),),
       'key=%s' % api_key
    return '%s%s' % (STATIC_MAPS_URL, '&'.join(params))#efficient concatenation

def geocode(api_key, location, reverse=False, timeout=2):
    Returns a coordinate tuple corresponding to 
    location address. Alternatevily, returns place name,
    given location coordinates in string format, 
    separated by comma or space.  
        xml = _get_geocode_xml(api_key, location, timeout)
        return _get_coords(xml, reverse)
    except IOError:
        return None, None

def _get_geocode_xml(api_key, location, timeout=2):
    url = _get_geocode_url(api_key, location)
    status_code, response = http.request('GET', url, timeout=timeout)
    return response

def _get_geocode_url(api_key, location, n=1):
    if isinstance(location, unicode):
        location = location.encode('utf8')
    params = urlencode({'geocode': location, 'key': api_key, 'results': n})
    return '%s%s' % (GEOCODE_URL, params)

def _get_coords(response, reverse):
        dom = xml.dom.minidom.parseString(response)
        pos_elem = dom.getElementsByTagName(reverse and 'text' or 'pos')[0]
        pos_data = pos_elem.childNodes[0].data
        if reverse: 
            return pos_data
            return tuple(pos_data.split())
    except IndexError:
        return None, None