Find a street from just about any city + state Google Maps API

4

I'm using the Google Map API, and I'm having a question: how can I search for a single street in a city? 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 looks like this:

     <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>
    
asked by anonymous 05.11.2015 / 15:24

1 answer

1

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

link :

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);
        }
    });
}
    
05.11.2015 / 17:33