Google Places JavaScript Autocomplete: can I remov

2020-02-04 20:44发布

问题:

I have the following jQuery code which works well with getting the city list for the selected country.

var city;   var place;

$('#city').on('focus',function(){
    input = this, options = {
        types: ['(cities)'],
        componentRestrictions: {
            country: $('#country option:selected').val()
            }
    };
    city = new google.maps.places.Autocomplete(input, options);
    google.maps.event.addListener(city, 'place_changed', function() {
        place = city.getPlace();
        $(input).val(place.address_components[0].long_name);
    })
})

Basically, once the person selects the place, it replaces the value in the input box with the "city" value without the country.

It looks a little stupid having City, Country in the dropdown menu when the user has already selected a country, so does anybody know if it is possible to display JUST the city name if you have defined a componentRestrictions value restricting the results to a country?

I find my current method of setting it once the selection has been made to be a bit... rubbish really...

回答1:

When invoking Google API, specify attribute "region":

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false&key=your_key&language=fr&region=FR"></script>

Then, when you create an Autocomplete object, specify the country in the componentRestriction attribute, so that it reflects the region you specified:


    new google.maps.places.Autocomplete(
        $("#my-input-field").get(0),
        {
            componentRestrictions: {country: "fr"},
            types: ["(regions)"]
        }
    );



回答2:

Also you can help yourself by css - hiding last span (=state) in autocomplete item.

.pac-item > span:last-child {
    display: none;
}


回答3:

The short answer is: the response content in the Autocomplete is controlled by Google (you mention this in one of your comments) and the Autocompleteapi-doc doesn't provide a way to customize the response text that is displayed, other than changing the placeholder textdev-guide. The solution you are using is about the best option you have (and is a little reactive, but I don't know if its really "rubbish").

Other than that, if you are less than satisfied with that approach, you could always just create your own input area and take complete control of the request-response back and forth yourself. You can use the Places Librarydev-guide directly and take complete control of everything that is shown.



回答4:

I wait 100 milleseconds, and then replace the text box with the content I want.

Except in my case I want a blank box, but insert a single space.