def MultispectralRGeocode(lat,lng):
    ticket = "76333D50-F9F4-4088-A9D7-DE5B09F9C27C"
    url  = "http://www.geoportal.com.br/xgeocoder/cxinfo.aspx?x="+lng+"&y="+lat+"&Ticket="+str(ticket)
    page = urllib2.urlopen(url)
    conteudo = page.read()
    page.close()
    geocodexml = ElementTree.fromstring(conteudo)
    address = geocodexml.findall("INFO")
     #self.stdout.write(address[0].text+","+address[0].get("NroIni")+"-"+address[0].get("NroFim")+","+address[0].get("Bairro")+","+address[1].text+"-"+address[2].text+","+address[0].get("CEP"))
    if (address != []):
        c = CachedGeocode(
            lat = float(lat),
            lng = float(lng),
            full_address = "",
            number = address[0].get("NroIni")+"-"+address[0].get("NroFim"),
            street = title(lower(address[0].text)),
            city = title(lower(address[1].text)),
            state = address[2].text,
            country = "Brasil",
            postal_code = address[0].get("CEP"),
            administrative_area = title(lower(address[0].get("Bairro")))
        )
        c.full_address = c.street+" "+c.number+", "+c.administrative_area+" - "+c.city+", "+c.state
        c.save()
        
        return [c.full_address,c.street+" "+c.number+", "+c.administrative_area,c.city,c.state,c.postal_code]
    else: 
        raise NotImplementedError
def Geocode(array):    

    ticket = "awFhbDzHd0vJaWVAzwkLyC9gf0LhbM9CyxSLyCH8aTphbIOidIZHdWOLyCtq"
    
    url = "webservices.apontador.com.br"
    
    results = []
        
    for a in array:
        city = array[a]['city']
        state = array[a]['state']
        number = array [a]['number']
        street = array[a]['address']
        
        xml = '<?xml version="1.0" encoding="utf-8"?><soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope"><soap12:Body><getXY xmlns="http://webservices.maplink2.com.br"><address><street>'+street+'</street><houseNumber>'+str(number)+'</houseNumber><zip></zip><district></district><city><name>'+city+'</name><state>'+state+'</state></city></address><token>'+ticket+'</token></getXY></soap12:Body></soap12:Envelope>'
        print xml
        conn = httplib.HTTPConnection(url,timeout=3)
        headers = {"Content-type":"text/xml; charset=\"UTF-8\""}
        conn.request("POST", "/webservices/v3/AddressFinder/AddressFinder.asmx", xml, headers)
        response = conn.getresponse()
        conteudo = response.read()
        conn.close()
        
        
        
        #<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><getMapResponse xmlns="http://webservices.maplink2.com.br"><getMapResult><url>http://teste.webservices.maplink2.com.br/output/</url><extent><XMin>-49.2962339</XMin><YMin>-26.94037873</YMin><XMax>-43.2075</XMax><YMax>-21.356430578</YMax></extent></getMapResult></getMapResponse></soap:Body></soap:Envelope>
    
        if response.status == 200:
            gxml = ElementTree.fromstring(conteudo)
            
            lng = gxml.find(".//{http://webservices.maplink2.com.br}x")
            lat = gxml.find(".//{http://webservices.maplink2.com.br}y")
            
            try:
                c = CachedGeocode.objects.get(Q(lng=lng.text) & Q(lat=lat.text))
            
            except ObjectDoesNotExist:    
                c = CachedGeocode(
                    lat = float(lat.text),
                    lng = float(lng.text),
                    full_address = "",
                    number = number,
                    street = title(lower(smart_str(street, encoding='utf-8', strings_only=False, errors='strict'))),
                    city = title(smart_str(city, encoding='utf-8', strings_only=False, errors='strict')),
                    state = state,
                    country = "Brasil",
                    #postal_code = postal.text,
                    #administrative_area = title(lower(address[0].get("Bairro")))
                )
        
                c.full_address = smart_str(c.street, encoding='utf-8', strings_only=False, errors='strict')+" "+str(c.number)+", "+smart_str(c.city, encoding='utf-8', strings_only=False, errors='strict')+", "+str(c.state)
                try:
                    c.save()
                except:
                    pass
            except MultipleObjectsReturned:
                c = CachedGeocode.objects.filter(Q(lng=lng.text) & Q(lat=lat.text))[0]
    
            result = {}
            result['lng'] = lng.text
            result['lat'] = lat.text
            results.append(result)
            
    json = simplejson.dumps(results)
    return HttpResponse(json, mimetype='application/json')