Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
        }
like image 673
Artyom Chernetsov Avatar asked Apr 12 '12 14:04

Artyom Chernetsov


2 Answers

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 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.

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 filed with the full address, so you have to 'wait' for google to update and then force your change by waiting some millseconds.

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

like image 190
asanchez Avatar answered Oct 02 '22 20:10

asanchez


EDIT

You can't. I had it the other way around, that you were just looking for a city. There is no way to only print out the street name (I'm assuming that's a street name) from the address component.


OPPOSITE OF WHAT WAS ASKED

From the docs:

the (cities) type collection instructs the Place service to return results that match either locality or administrative_area3.

var input = document.getElementById('searchTextField');
var options = {
  bounds: defaultBounds,
  types: ['(cities)']
};

autocomplete = new google.maps.places.Autocomplete(input, options);
like image 32
tkone Avatar answered Oct 02 '22 18:10

tkone