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 MaplinkRGeocode(lat,lng):
    
    ticket = "awFhbDzHd0vJaWVAzwkLyC9gf0LhbM9CyxSLyCH8aTphbIOidIZHdWOLyCtq"

    url = "http://webservices.apontador.com.br"
    
    xml = '''<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><getAddress xmlns="http://webservices.maplink2.com.br"><point><x>'''+str(lng)+'''</x><y>'''+str(lat)+'''</y></point><token>'''+str(ticket)+'''</token><tolerance>'''+str(10)+'''</tolerance></getAddress></soap:Body></soap:Envelope>'''
    
    try:
        conn = httplib2.Http(timeout=3)
        headers = {"Content-type":"text/xml; charset=\"UTF-8\"","SOAPAction":"http://webservices.maplink2.com.br/getAddress","Host":"teste.webservices.apontador.com.br"}
        resp, content = conn.request(url+ "/webservices/v3/AddressFinder/AddressFinder.asmx", "POST", body=xml,headers=headers)
        response = content
        conteudo = content
    #try:
    #    conn.request("POST", "/webservices/v3/AddressFinder/AddressFinder.asmx", xml, headers)
    #    response = conn.getresponse()
     #   conteudo = response.read()
     #   conn.close()
       
    except Exception as err:
      print(err)
      raise NotImplementedError

    if resp.status == 200:
        try:
            #print conteudo
            gxml = ElementTree.fromstring(conteudo)
            
            street = gxml.find(".//{http://webservices.maplink2.com.br}street")
            if street.text is None: street.text = ""
            city = gxml.find(".//{http://webservices.maplink2.com.br}name")
            if city.text is None: city.text = ""
            state = gxml.find(".//{http://webservices.maplink2.com.br}state")
            if state.text is None: state.text = ""
            number = gxml.find(".//{http://webservices.maplink2.com.br}houseNumber")
            if number.text is None: number.text = ""
            postal = gxml.find(".//{http://webservices.maplink2.com.br}zip")
            if postal.text is None: postal.text = ""
            
            c = CachedGeocode(
                lat = float(lat),
                lng = float(lng),
                full_address = "",
                number = number.text,
                street = title(lower(street.text)),
                city = title(city.text),
                state = state.text,
                country = "Brasil",
                postal_code = postal.text,
                #administrative_area = title(lower(address[0].get("Bairro")))
            )
        
            c.full_address = c.street+" "+ c.number+", "+c.city+", "+c.state
            #try:
            #    c.save()
            #except:
            #    pass
        except Exception as err:
            print(err)
            pass
        try:
            return [c.full_address,c.street+" "+c.number,c.city,c.state,c.postal_code]
        except TypeError as err:
            print (err)
            print c.full_address, "str>", c.street,"num>", c.number,"cty>",c.city,"sta>" , c.state,"pos>",c.postal_code,c.lat,c.lng
        return [c.full_address,]
    else:
        pass
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')