【问题标题】:Google Autocomplete with Apartment Number带有公寓号码的 Google 自动填充功能
【发布时间】:2015-06-26 18:50:26
【问题描述】:

当用户将公寓号码添加到他们的地址时,自动填充似乎认为它正在查看邮政编码,并更改建议的匹配项:

6250 好莱坞大道 #20

有没有办法让它工作,或者如果没有,有一种方法可以忽略公寓号码并将其与表单提交一起作为单独的值发送? (请记住,用户可能会使用 #、Unit、Apt 等来定义他们的单位编号)

var placeSearch, autocomplete;

var componentForm = {
    street_number:                  'short_name',
    route:                          'short_name',
    locality:                       'long_name',
    administrative_area_level_1:    'short_name',
    country:                        'long_name',
    postal_code:                    'short_name'
};

function initialize(){

    autocomplete = new google.maps.places.Autocomplete(
        (document.getElementById('autocomplete-address')),
        { types: ['geocode'] });
        google.maps.event.addListener(autocomplete, 'place_changed', function(){
            fillInAddress();
        }
    );

}

function fillInAddress(){

    var place = autocomplete.getPlace();

    for(var component in componentForm){

        document.getElementById(component).value = '';
        document.getElementById(component).disabled = false;

    }

    for(var i = 0; i < place.address_components.length; i++){

        var addressType = place.address_components[i].types[0];

        if(componentForm[addressType]){

            var val = place.address_components[i][componentForm[addressType]];

            document.getElementById(addressType).value = val;

        }

    }

}

【问题讨论】:

    标签: google-maps-api-3 autocomplete street-address


    【解决方案1】:

    似乎不存在将自动完成 API 设置为忽略 apt 编号的设置,但是,我们可以在将字符串传递给 API 之前修剪文本。

    在您的 autocomplete = new google.maps.places.Autocomplete( 中,您可以执行以下操作:

    document.getElementById('autocomplete-address').replace(/#.*/g,"");
    

    由于document.getElementById('autocomplete-address')返回一个字符串,我们可以用.replace(/#.*/g,"")将#number替换成一个空字符串

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 2015-01-20
      相关资源
      最近更新 更多