Search only street of any city + state Google Maps API

Asked

Viewed 1,365 times

4

I’m using the Google Map API, and I’m having a question: how can I search for just one city street? If that street is not found in a particular city, nothing happens.

I have basically 3 fields: a select for the state, another for the cities of the respective state, and a text field for the street

my code is as follows:

     <div class="form-group">
                <fieldset>
                    <label>Estado</label>
                    <select class="form-control" id="estado" name="estado">
                    <option id="padraoEstado">Selecione um estado</option>
                    <?php 
                        $sql = "SELECT * FROM tb_estados";
                        $query = $conn->query($sql);
                        while($post = $query->fetch_assoc()){ 
                        ?>
                            <option value="<?php echo $post['ID_state']; ?>"><?php echo $post['uf']; ?> </option>
                        <?php
                        }
                        ?>
                    </select> 
                        <script type="text/javascript">
                            $(document).ready(function(){
                                $("#estado").change(function(){
                                    $("#endereçoEmpresa").val("");
                                    $("#padraoEstado").remove();
                                    var valorEstado = $('#estado option:selected').val();
                                    $.ajax({
                                        url: "carregarCidades.php",
                                        type: "POST",
                                        dataType: "html",
                                        data:{
                                            valorEstado: valorEstado
                                        },
                                        success: function(data){
                                            $("#cidade").removeAttr("disabled");
                                            $("#cidade").append().html(data);
                                            var valorCidade = $('#cidade option:selected').text();
                                            $("#mapCompany").show();
                                            marker = null;
                                            initialize();
                                            codeAddress();

                                        },
                                        error: function(data){
                                            alert(data)
                                        }
                                    });
                                });
                            });
                        </script>
                    <label>Cidade</label>
                    <select disabled class="form-control" id="cidade" name="cidade">
                    </select> 
                </fieldset>
            </div>
            <script type="text/javascript">
                $(document).ready(function(){
                    $("#cidade").change(function(){
                        $("#endereçoEmpresa").val("");
                        codeAddress();
                    });

                    $("#endereçoEmpresa").change(function(){    
                        codeAddress();
                    });
                });
            </script>
            <div class="form-group">
                <label >Endereço da Empresa</label>
                <input type="text"  id="endereçoEmpresa" name="endereçoEmpresa" class="form-control" />
            </div>
            <script type="text/javascript">
                var geocoder;
                var map;
                var marker;
                 function initialize() {
                    função para iniciar o mapa
}
    function codeAddress(){
                var valorCidade = $('#cidade option:selected').text();
                var valorEstado = $('#estado option:selected').text();
                var valorEndereco = $("#endereçoEmpresa").val();
                var address = valorEndereco + ", " + valorCidade + " - " + valorEstado;

                geocoder.geocode( { 'address': address + ', Brasil', 'region': 'BR'}, function(results, status) {
                  if (status == google.maps.GeocoderStatus.OK) {
                    map.setCenter(results[0].geometry.location);
                     if(!marker){
                        marker = new google.maps.Marker({
                        map: map,
                        position: results[0].geometry.location
                        }); 
                     }else{
                        marker.setPosition(results[0].geometry.location);
                     }
                    var latitude = results[0].geometry.location.lat();
                    var longitude = results[0].geometry.location.lng()
                    $("#lat").val(latitude);
                    $("#lng").val(longitude);
                  }else{
                    alert("A API de mapas do Google não conseguiu achar esta localização por algum motivo: " + status);
                  }
                });
              }
            </script>
  • Do the following in your query that goes to the API: <state>, <city>, <address>

  • Alternatively: https://developers.google.com/maps/documentation/javascript/examples/geocoding-component-restriction. You may restrict by city zip

2 answers

1

You can restrict by the beginning of the city zip code:

https://developers.google.com/maps/documentation/javascript/examples/geocoding-component-restriction:

function initMap() {
    var geocoder = new google.maps.Geocoder;
    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 8,
        center: {lat: -33.865, lng: 151.209}
    });

    document.getElementById('submit').addEventListener('click', function() {
        geocodeAddress(geocoder, map);
    });
}

function geocodeAddress(geocoder, map) {
    geocoder.geocode({
        componentRestrictions: {
            /* Aqui seta o pais */
            country: 'br',
            /* Aqui o inicio do CEP */
            postalCode: '89235'
        }
    }, function(results, status) {
        if (status === google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
            new google.maps.Marker({
                map: map,
                position: results[0].geometry.location
            });
        } else {
            window.alert('Geocode was not successful for the following reason: ' +
            status);
        }
    });
}

0

Friendly talk!

We were facing the same problem and ended up building a Javascript solution capable of restricting the address the way you want.

The Problem

The reality is that the Google Places API methods do not give us many options to restrict addresses, it is only possible to restrict, for example, the country and geographical coordinates (if you are able to obtain them in the context of your application).

However, it remains a little complicated for users to enter the full address (neighborhood, city, state, etc.) every time they need a validated address (at least in my case of use which is firefighter emergency care).

Solution

It is not 100% that will not return unwanted results, but it will save a lot of time and user typing effort.

Basically this script, underneath the scenes, adds to the request the necessary restrictions, before sending to Google servers, in a transparent way for the user.

It is used "service.getPlacePredictions" and "google.maps.Places.Autocompleteservice" and has been implemented in a way that billing is of type "Autocomplete without Places Details - Per Session", which means that it will be charged only once for the entire process that comprises from the beginning of the typing of the address by the user, until the moment he clicks on one of the suggestions presented (the cheapest form available).

Another advantage of using this custom autocomplete, rather than the standard google widget, is that the autocomplete text field will not be blocked if there is a problem with the Key API, such as quota limits, payment, etc. So the user can enter some address and in the future the system administrators can give the appropriate treatment to non-validated addresses.

Places API and Maps Javascript API must be enabled on your.cloud.google.com console.

Anyway, below is all you need to make the developed component work in your application.

<html>
   <head>
      <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
      <meta content="utf-8" http-equiv="encoding">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <link rel="stylesheet" type="text/css" href="style.css">
   </head>
   <body>
      <p>This example uses service.getPlacePredictions and google.maps.places.AutocompleteService what means that the billing stands for "Autocomplete without Places Details - Per Session"</p>
      <!--Make sure the form has the autocomplete function switched off:-->
      <form autocomplete="off" action="/action_page.php">
         <div class="autocomplete" style="width:300px;">
            <p><input id="estado" type="text" name="estado" placeholder="Estado" value="SC"></p>
            <p><input id="cidade" type="text" name="cidade" placeholder="Cidade"value="FLORIANOPOLIS"></p>
            <p><input id="bairro" type="text" name="bairro" placeholder="Bairro" value="CENTRO"></p>
            <p><input id="numero" type="text" name="numero" placeholder="Numero" value="10"></p>
            <input id="logradouro" type="text" name="logradouro" placeholder="Logradouro">
         </div>
         <input type="submit">
      </form>
      <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
      <script async defer src="https://maps.googleapis.com/maps/api/js?key=GOOGLE_API_KEY&libraries=places" type="text/javascript"></script>
      <script src="./autocomplete.js" type="text/javascript"></script>
      <script type="text/javascript">
         let autocomplete = new RestrictedAutocomplete(document.getElementById("logradouro"), function () {
            console.log(this.lastResultBusca);
            console.log(this.lastResultEnderecoCompleto);
            console.log(this.lastResultNumero);
            console.log(this.lastResultNumeroA);
            console.log(this.lastResultLogradouro);
            console.log(this.lastResultLogradouroA);
            console.log(this.lastResultBairro);
            console.log(this.lastResultBairroA);
            console.log(this.lastResultCidade);
            console.log(this.lastResultCidadeA);
            console.log(this.lastResultEstado);
            console.log(this.lastResultEstadoA);
            console.log(this.lastResultPais);
            console.log(this.lastResultPaisA);
            console.log(this.lastResultCEP);
            console.log(this.lastResultCEPA);
            console.log(this.lastResultId);
            console.log(this.lastResultLatitude);
            console.log(this.lastResultLongitude);
         });
         autocomplete.setRestrictions(document.getElementById("estado"), 
            document.getElementById("cidade"), 
            document.getElementById("bairro"), 
            document.getElementById("numero"));
      </script>
   </body>
</html>

Autocomplete working:

autocomplete working

Autocomplete after user selects an address: an address has been selected

For more details see project on Github.

I hope it helps you!

Browser other questions tagged

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