【问题标题】:Google maps api Auto Complete for country国家/地区的 Google 地图 api 自动完成
【发布时间】:2017-10-20 10:15:06
【问题描述】:

如果选择的话,我只想获取特定国家/地区的地址。我的代码是:

var country="";
    $("select[name='country_id']").change(function () {
        co=$("select[name='country_id']").val();

    });
    function initialize() {
        var options={};
        if(country){
         options = {
                types: ['geocode'],
                componentRestrictions: {country: country}
            };
        }else{
            options = {
                types: ['geocode']
            };
        }

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

        google.maps.event.addListener(autocomplete, 'place_changed', function () {
        //...
        });
    }
    google.maps.event.addDomListener(window, 'load', initialize);

但我的国家/地区值始终为空。 我如何处理国家以获取其价值?请帮帮我。谢谢!

【问题讨论】:

  • country=$("select[name='country_id']").val(); 而不是 co=$("select[name='country_id']").val();
  • 是的,但它也不起作用:var country=""; $("select[name='country_id']").change(function () { country=$("select[name='country_id']").val(); }); function init() { alert(country); var input = document.getElementById('locationTextField'); var autocomplete = new google.maps.places.Autocomplete(input); } google.maps.event.addDomListener(window, 'load', init); 警告在页面加载时显示一次,然后不显示任何内容
  • 它没有帮助我
  • 在出现问题的地方添加 Fiddle 工作示例

标签: google-maps autocomplete google-maps-autocomplete


【解决方案1】:

您必须每次使用新国家/地区 onchange 初始化自动完成

Fiddle demo

JS

var country = "";
$("select[name='country_id']").change(function() {
  country = $("select[name='country_id']").val();
  $('#searchTextField').attr('placeholder','search form '+$("select[name='country_id'] option:selected").text())
  $('#input').show();
  initialize()
});

function initialize() {
  var input = document.getElementById('searchTextField');
  var options = {
    componentRestrictions: {
      country: country
    }
  };

  var autocomplete = new google.maps.places.Autocomplete(input, options);

  google.maps.event.addListener(autocomplete, 'place_changed', function() {

    var place = autocomplete.getPlace();
    var lat = place.geometry.location.lat();
    var long = place.geometry.location.lng();
    alert(lat + ", " + long);

  });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-25
    • 1970-01-01
    • 2015-03-09
    • 1970-01-01
    • 2012-07-02
    • 1970-01-01
    • 2019-08-22
    相关资源
    最近更新 更多