Search CEP by PHP Street

2
  

First of all, I need to get the zip code down the street, that is, I do not have the zip code.   and I have the address, I need to find the zip code by the address. So please do not relate this question with Search Street by Zip Code

Problem

I have PHP code that searches for streets by zip, however I need otherwise, I need to search zip through the street, city and state. Is this possible?

Important Information for Problem Solving

The WebService ViaCEP It offers CEP and IBGE webservice for free, among the functions it also has to search the ZIP code on the street, however I can not adapt the functions in the code, the error or does not work, nothing appears. In addition to leaving the street search code by zip, I'll also leave the função linked to how it works to search the street for the zip.

Search Street by Zip Code

  Exemplo: viacep.com.br/ws/UF/Cidade/Rua/json/

Current Code

 <html>
 <head>
 <title>ViaCEP Webservice</title>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

 <!-- Adicionando Javascript -->
 <script type="text/javascript" >

 function limpa_formulário_cep() {
        //Limpa valores do formulário de cep.
        document.getElementById('rua').value=("");
        document.getElementById('bairro').value=("");
        document.getElementById('cidade').value=("");
        document.getElementById('uf').value=("");
        document.getElementById('ibge').value=("");
}

function meu_callback(conteudo) {
    if (!("erro" in conteudo)) {
        //Atualiza os campos com os valores.
        document.getElementById('rua').value=(conteudo.logradouro);
        document.getElementById('bairro').value=(conteudo.bairro);
        document.getElementById('cidade').value=(conteudo.localidade);
        document.getElementById('uf').value=(conteudo.uf);
        document.getElementById('ibge').value=(conteudo.ibge);
    } //end if.
    else {
        //CEP não Encontrado.
        limpa_formulário_cep();
        alert("CEP não encontrado.");
    }
}

function pesquisacep(valor) {

    //Nova variável "cep" somente com dígitos.
    var cep = valor.replace(/\D/g, '');

    //Verifica se campo cep possui valor informado.
    if (cep != "") {

        //Expressão regular para validar o CEP.
        var validacep = /^[0-9]{8}$/;

        //Valida o formato do CEP.
        if(validacep.test(cep)) {

            //Preenche os campos com "..." enquanto consulta webservice.
            document.getElementById('rua').value="...";
            document.getElementById('bairro').value="...";
            document.getElementById('cidade').value="...";
            document.getElementById('uf').value="...";
            document.getElementById('ibge').value="...";

            //Cria um elemento javascript.
            var script = document.createElement('script');

            //Sincroniza com o callback.
            script.src = '//viacep.com.br/ws/'+ cep + '/json/?callback=meu_callback';

            //Insere script no documento e carrega o conteúdo.
            document.body.appendChild(script);

        } //end if.
        else {
            //cep é inválido.
            limpa_formulário_cep();
            alert("Formato de CEP inválido.");
        }
    } //end if.
    else {
        //cep sem valor, limpa formulário.
        limpa_formulário_cep();
    }
};

</script>
</head>

<body>
<!-- Inicio do formulario -->
  <form method="get" action=".">
    <label>Cep:
    <input name="cep" type="text" id="cep" value="" size="10" maxlength="9"
           onblur="pesquisacep(this.value);" /></label><br />
    <label>Rua:
    <input name="rua" type="text" id="rua" size="60" /></label><br />
    <label>Bairro:
    <input name="bairro" type="text" id="bairro" size="40" /></label><br />
    <label>Cidade:
    <input name="cidade" type="text" id="cidade" size="40" /></label><br />
    <label>Estado:
    <input name="uf" type="text" id="uf" size="2" /></label><br />
    <label>IBGE:
    <input name="ibge" type="text" id="ibge" size="8" /></label><br />
  </form>
</body>

</html>

Summary

I practically need to adapt this PHP code to use as Unknown Zip Code.

    
asked by anonymous 04.04.2016 / 16:37

2 answers

5

I'm not much time to comment, as I usually do.

But since you made me discover this API, then I'll try to help. Unfortunately, using pure JS, for me, is complicated after it becomes habit to use JQuery, so I used it, but nothing prevents it from converting it to pure JS!

Usually looks like this:

var inputsCEP = $('#logradouro, #bairro, #localidade, #uf, #ibge');
var inputsRUA = $('#cep, #bairro, #ibge');
var validacep = /^[0-9]{8}$/;

function limpa_formulário_cep(alerta) {
  if (alerta !== undefined) {
    alert(alerta);
  }

  inputsCEP.val('');
}

function get(url) {

  $.get(url, function(data) {

    if (!("erro" in data)) {

      if (Object.prototype.toString.call(data) === '[object Array]') {
        var data = data[0];
      }

      $.each(data, function(nome, info) {
        $('#' + nome).val(nome === 'cep' ? info.replace(/\D/g, '') : info).attr('info', nome === 'cep' ? info.replace(/\D/g, '') : info);
      });



    } else {
      limpa_formulário_cep("CEP não encontrado.");
    }

  });
}

// Digitando RUA/CIDADE/UF
$('#logradouro, #localidade, #uf').on('blur', function(e) {

  if ($('#logradouro').val() !== '' && $('#logradouro').val() !== $('#logradouro').attr('info') && $('#localidade').val() !== '' && $('#localidade').val() !== $('#localidade').attr('info') && $('#uf').val() !== '' && $('#uf').val() !== $('#uf').attr('info')) {

    inputsRUA.val('...');
    get('https://viacep.com.br/ws/' + $('#uf').val() + '/' + $('#localidade').val() + '/' + $('#logradouro').val() + '/json/');
  }

});

// Digitando CEP
$('#cep').on('blur', function(e) {

  var cep = $('#cep').val().replace(/\D/g, '');

  if (cep !== "" && validacep.test(cep)) {

    inputsCEP.val('...');
    get('https://viacep.com.br/ws/' + cep + '/json/');

  } else {
    limpa_formulário_cep(cep == "" ? undefined : "Formato de CEP inválido.");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><formmethod="get" action=".">
  <label>Cep:
    <input name="cep" type="text" id="cep" value="" size="10" maxlength="9">
  </label>
  <br />
  <label>Rua:
    <input name="rua" type="text" id="logradouro" size="60" />
  </label>
  <br />
  <label>Bairro:
    <input name="bairro" type="text" id="bairro" size="40" />
  </label>
  <br />
  <label>Cidade:
    <input name="cidade" type="text" id="localidade" size="40" />
  </label>
  <br />
  <label>Estado:
    <input name="uf" type="text" id="uf" size="2" />
  </label>
  <br />
  <label>IBGE:
    <input name="ibge" type="text" id="ibge" size="8" />
  </label>
  <br />
</form>

How it works:

  

A summary of "critical parts" that can generate some doubt:

Typing selection:

  • Entering the zip code will https://viacep.com.br/ws/{CEP}/json/ .
  • If you enter the STREET, CITY and UF will query% with%

Connection

Modified from JSONP to JSON, using $ .get (), to minimize code repetition, a function with a name of https://viacep.com.br/ws/{UF}/{CIDADE}/{RUA}/json/ was created.

Array Check

By default, when you type the ZIP code, you just return an ARRAY, so you just have to loop it. While typing the address (Street, City, State) the site returns an OR MORE array.

Example:

Pesquisa por CEP = {'nome':'dado'}
Pesquisa por Endereço = [{'nome':'dado'}, {'nome':'dado'}]

This is why get has been created to check if there are multiple ZIP codes / arrays. That way it will loop using always the first!

Attribute Object.prototype.toString.call(data) :

This was created so that if the user enters a new address it is necessary to modify all the data of Street, City and State so that it makes a new request. The info stores the same content as info , so if the user enters a new street without changing the city and the state will not make a new request.

This is optional, just to avoid making multiple requests. In order to be re-verified, all Street, City and State data must be changed.

    
05.04.2016 / 16:33
1

From what I understand the search for street must pass city and state as well.

It would look something like this:

var rua = document.getElementById('rua').value=("");
var cidade = document.getElementById('cidade').value=("");
var uf = document.getElementById('uf').value=("");

script.src = '//viacep.com.br/ws/'+ uf + '/'+ cidade + '/'+ rua + '/json/?callback=meu_callback';

        //Insere script no documento e carrega o conteúdo.
        document.body.appendChild(script);
    
04.04.2016 / 17:58