【问题标题】:Maps API autocomplete suggestion won't replace value of inputMaps API 自动完成建议不会替换输入值
【发布时间】:2019-01-08 18:32:02
【问题描述】:

我有一个使用 Google Maps API 自动完成的输入字段。我想将该输入中的数据保存到数据库(Firebase)。但问题是,在选择自动完成结果并提交表单后,它显示的值保存了 我在选择自动完成之前输入的内容

前:

我在输入“New”后从自动完成中选择“New York City...” 即使输入字段显示“纽约市”,它提交的只是“新”

出于演示目的,我将它连接到 Google Map iframe:此处找到完整代码:http://codepen.io/Auzy/pen/wJyXKR?editors=1111

const searchInput = document.getElementById('searchTextField');
const autocomplete = new google.maps.places.Autocomplete(searchInput);

searchInput.addEventListener("change", () => {
    let addr = searchInput.value;
    console.log(addr)
    let embed= "<iframe frameborder='0' scrolling='no' marginheight='0' marginwidth='0' src='https://maps.google.com/maps?&amp;q="+ encodeURIComponent( addr ) + "&amp;output=embed'></iframe>";  

    $('.place').html(embed);                                         
});
function getInput(){

    var addr = document.getElementById('searchTextField').value;


        var embed= "<iframe frameborder='0' scrolling='no' marginheight='0' marginwidth='0' src='https://maps.google.com/maps?&amp;q="+ encodeURIComponent( addr ) + "&amp;output=embed'></iframe>";  

        $('.place').html(embed);

};

【问题讨论】:

    标签: javascript google-maps google-maps-api-3


    【解决方案1】:

    你好_伙计,

    当您调用您的代码时,searchInput.value 似乎仍未更新。

    在执行代码之前尝试设置超时 - 请参阅分叉的 codepen HERE

    所以你可以像这样解决你的问题:

    searchInput.addEventListener("change", () => {
        // Wrap in setTimeout, so you give time searchInput.value to be updated
        setTimeout(function() {
            let addr = searchInput.value;
            console.log(addr)
            let embed = "<iframe frameborder='0' scrolling='no' marginheight='0' marginwidth='0' src='https://maps.google.com/maps?&amp;q=" + encodeURIComponent(addr) + "&amp;output=embed'></iframe>";
    
            $('.place').html(embed);
        }, 100); 
    });
    

    结论

    google.maps.places.Autocomplete 更新 &lt;input&gt; 的值之前存在延迟

    【讨论】:

    猜你喜欢
    • 2020-08-21
    • 2012-01-16
    • 2014-03-15
    • 1970-01-01
    • 2013-04-29
    • 2015-10-19
    • 2012-03-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多