Search code examples
google-maps-api-3

Google maps Autocomplete: output only address without country and city


I use Places library to autocomplete address input. Search is limited to only one city, and I get output like this:

"Rossiya, Moskva, Leninskiy prospekt 28"

How to hide "Rossiya, Moskva"? ...

My query:

function() {
        // Search bounds
        var p1 = new google.maps.LatLng(54.686534, 35.463867);
        var p2 = new google.maps.LatLng(56.926993, 39.506836);
        self.options = {
            bounds : new google.maps.LatLngBounds(p1, p2),
            componentRestrictions: {country: 'ru'},
        };

        var elements = document.querySelectorAll('.address');

        for ( var i = 0; i < elements.length; i++) {
            var autocomplete = new google.maps.places.Autocomplete(elements[i],
                    self.options);
        }

Solution

  • You can but you have to replace the value of the input field in two places.

    Example:

    var autocomplete = new google.maps.places.Autocomplete(input, placesOptions);
    var input = document.getElementById('searchTextField');
    

    inside the 'place_changed' event you need to do the following:

    placeResult = autocomplete.getPlace();
    //This will get only the address
    input.value = placeResult.name;
    

    This will change the value in the searchtextfield to the street address.

    The second place is a bit tricky:

    input.addEventListener('blur', function(){
    // timeoutfunction allows to force the autocomplete field to only display the street name.
    if(placeResult){ setTimeout(function(){ input.value = placeResult.name; }, 1); } });
    

    The reason why we have to do this is because if you only add the event listener for blur, google places will populate the input field with the full address, so you have to 'wait' for google to update and then force your change by waiting some miliseconds.

    Try it without the setTimeout function and you will see what I mean.