简体   繁体   中英

Google places api for javascript autocomplete restrict to suggestions

I am using this api:

google.maps.places.Autocomplete

I need to be able to restrict my text field to only the results by the api, and not allow free text selection.

Here is my code:

var ac = new google.maps.places.Autocomplete($('#txt').get(0));
ac.place_changed = function () {
    // TODO: add code to verify address if required
}

Is there some setting in the Autocomplete to do this...?

I managed to find a solution by applying a few things.

First of all, the form tag needs onsubmit with return :

<form action="..." method="get" onsubmit="return formSubmitted(this);">

2nd, the autocomplete should set a variable (say ac_var ) with acquired place data

ac.place_changed = function () {
    var pl = ac.getPlace();
    var addr = pl.address_components;
    ac_var = addr[0].long_name;
}

3rd, the function in javascript:

function formSubmitted(frm) {
    if ( frm.txt.value == '' || ac_var == '' )
        return false;

    return true;
}

Some checks on the addr[0].long_name to check that it does exist or not should also be good.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM