0

スクリプトに苦労しています。基本的に、入力ボックスから country_code を読み取り、これを Google マップの場所の自動提案の国フィルターとして使用します。このコードは機能し、ここで見ることができます:

http://jsfiddle.net/spadez/5dqHg/23/

このフィールドから国コードを取得します。

<input class="hidden" id="#ctry" disabled="true" value="us"></input>

私の問題は、このフィールドが常に設定されるとは限らないことです。

<input class="hidden" id="#ctry" disabled="true" value=""></input>

しかし、これは自動提案を壊します。実際には、国フィルターを自動提案に適用して、すべての国の場所を表示するべきではありません。

sudo コードでは、次のようなものが必要だと思います。

var ctryiso = $("#ctry").val();
autocomplete = new google.maps.places.Autocomplete(input[0], {
  types: ["geocode"],
<if ctryiso !=null then>
  componentRestrictions: {
    country: ctryiso
  }
</if>

});

私もこのテクニックを試しましたが、成功しませんでした:

if (ctryiso) { options.componentRestrictions= { 'country': ctryiso }; }
var autocomplete = new google.maps.places.Autocomplete(input, options);

上記のように国入力ボックスに国制限フィルターがある場合にのみ国制限フィルターを設定する方法を誰かが教えてくれますか?

4

1 に答える 1

1

オプション変数を使用して、条件チェックの後に渡すことができます。

var ctryiso = $("#ctry").val();
var options;
if(ctryiso != ''){
    options = {
      types: ["geocode"],
      componentRestrictions: {
                 country: ctryiso
      }
    }
}else{
    options = {types: ["geocode"]}
}
autocomplete = new google.maps.places.Autocomplete(input[0], options); // <-- pass in the options

フィドル

ここまでコンパクトにできます。

var ctryiso = $("#ctry").val();
var options = {
     types: ["geocode"]
};
if(ctryiso != ''){
    options.componentRestrictions= { 'country': ctryiso };        
}
autocomplete = new google.maps.places.Autocomplete(input[0], options); 

フィドル

于 2013-06-10T14:44:15.627 に答える