Google Maps API自动填充功能 - 如何仅输出街道名称?

时间:2017-02-26 12:07:06

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

我有一个输入字段,只有地址返回。

但是当我输入街道名称时,输入字段会返回街道名称加上逗号和街道城市。

我收到了以下代码:

<script src="http://maps.google.com/maps/api/js?libraries=places&region=de&language=de&sensor=false"></script>
<input id="strasse" type="text" size="50">

 $(function(){     

    var input = document.getElementById('strasse');         
    var autocomplete = new google.maps.places.Autocomplete(input, {
        types: ["address"]
    });          

    $("#strasse").focusin(function () {
        $(document).keypress(function (e) {
            if (e.which == 13) {
                infowindow.close();

            }
        });
    });
});

EG:

我进入&#34; Teststreet&#34; 输出=&#34; Teststreet,慕尼黑&#34;

回报应该只是&#34; Teststreet&#34;。

有没有办法,删除&#34;,&#34;之后的所有内容。 (也许超过jQuery)?

1 个答案:

答案 0 :(得分:3)

您可以使用place_changed事件侦听器,然后从返回的内容中选择所需内容:

    <script>
    var input = document.getElementById('strasse');
    var autocomplete = new google.maps.places.Autocomplete(input, {
            types: ["address"]
        });     
     $(function(){     

        autocomplete.addListener('place_changed', fillInAddress);

        $("#strasse").focusin(function () {
            $(document).keypress(function (e) {
                if (e.which == 13) {
                    infowindow.close();

                }
            });
        });
    });

    function fillInAddress() {
        // Get the place details from the autocomplete object.
        var place = autocomplete.getPlace();
        if (typeof place.address_components[0] !== "undefined") {
            $(input).val(place.address_components[0].long_name);
        }
    }
     </script>

还可以很好地演示可以实现的目标here

在这个例子中,我们使用了返回的long_name类型的route。只需console_log(place.address_components);即可查看返回的完整列表。