Search ZIP by PHP Street

Asked

Viewed 8,946 times

2

First of all, I need to search the zip code down the street, which means I don’t have the zip code and I have the address, I need to find the zip code by the address. So please don’t link this question with Search Street by zip code

Problem

I have a PHP code that searches streets by zip code, but I need the opposite, I need you to search by street, city and state. This is possible?

Important Information for Troubleshooting

The Webservice Viacep Offers ZIP and IBGE webservice for free, among the functions he also has to search the zip code by the street, but I can not adapt the functions in the code, error or does not work, nothing appears. In addition to leaving the street search code by zip code, I will also leave the função linked to how it works to search the street by the zip code.

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

Practically need to adapt this PHP code, to use as CEP Unknown.

  • 1

    This Webservice you are using does not provide the search by address, but only by zip code. Has this site http://www.cepaberto.com/ which is also free that can help you because it allows various types of search

  • Yes @Marlontiedt, they even give an example - viacep.com.br/Ws/RS/Porto Alegre/Olavo/json/, but wanted to adapt the calls to the proper fields understand?

  • 1

    I hadn’t seen

  • 1

    +Favorite to see the API website after. P

3 answers

5


I’m running out of time to comment, as I usually do.

But as you made me discover this API, so I will try to help. Unfortunately using pure JS, for me, it is complicated after you get used to using Jquery, so I used, but nothing prevents you from converting it to pure JS!

It’s usually 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>
<form method="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 may generate some doubt:

Typing selection:

  • If you enter the zip code you will consult the https://viacep.com.br/ws/{CEP}/json/.
  • If you type STREET, CITY and UF will consult the https://viacep.com.br/ws/{UF}/{CIDADE}/{RUA}/json/

Connection

Modified from JSONP to JSON, using $.get(), to minimize code repetition a named function was created get.

Array check

By default when typed the zip code only returns an ARRAY, so just 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'}]

That is why the Object.prototype.toString.call(data) to check if there are multiple Ceps/Arrays. This way it will loop using the first!

Attribute info:

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

This is optional, just to avoid making multiple requests. In order to be necessary to make the new check all the data of Street, City and State must be changed.

  • Cara do not believe, @Inkeliz thank you very much for the answer, this is the solution to my problem and many other people believe, I sent the code in full to Viacep by email and asked to put the due credit to you. I really appreciate it, I had already given up hope on this question, great work friend

1

From what I understand the search for street needs to pass city and state too.

Would 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);

-3

Browser other questions tagged

You are not signed in. Login or sign up in order to post.