首页 文章

Google自动填充API - 格式输出结果

提问于
浏览
3

我正在尝试实施Google Places API,所以这是我的代码:

<!DOCTYPE html>
<html>
<head>
    <script src="http://codeorigin.jquery.com/jquery-1.10.2.min.js"></script>
    <script src="//maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places&location=0,0&radius=20000000&language=de"></script>
    <script>
        $(document).ready(function() {
            var el = $('#street').attr("placeholder", "")
                    , autocomplete = new google.maps.places.Autocomplete( ( el.get(0) ), { types: ['geocode'] } );

            el.bind("blur", function() {
                // blur is triggered before place_changed, as well as focus... so this is not working as well
            })

            google.maps.event.addListener(autocomplete, 'place_changed', function() {
                var place = autocomplete.getPlace();

                el.val(place.name); // this line is not working well - still default content showing !!!
            });
        })
    </script>
</head>
<body">
    <input type="text" id="street" style="width:400px;" />
</body>
</html>

Google自动填充功能正常,但我有一个要求 - 只显示街道名称和号码,而不是Google建议的完整地址 . 所以我可以通过在"place_changed"事件中运行 autocomplete.getPlace() 来获取所有信息 - 没有问题 .

问题是我不能用我的自定义文本覆盖自动完成输入值 - 我试图在“模糊”,“焦点”,“place_changed”事件中进行 - 仍然没有运气 . 请找一个我正在尝试的例子 . 此外 - 我需要避免文字闪烁,使其绝对用户友好 . 有人可以帮助我尝试吗?

JSFiddle:http://jsfiddle.net/8pGH2/

2 回答

  • 1

    我能用以下代码解决我的问题:

    $(document).ready(function() {
         var el = $('#street').attr("placeholder", "")
            , autocomplete = new google.maps.places.Autocomplete( ( el.get(0) ), { types: ['geocode'] } );
    
            el.bind("blur", function() {
              el.css("color", "#fff"); // this will prevent text flashing
            })
    
            google.maps.event.addListener(autocomplete, 'place_changed', function() {
               var place = autocomplete.getPlace();
    
                el.val(place.name);
    
                // this will override default Google suggestion
                setTimeout(function() {
                    el.val(place.name);
                    el.css("color", "");
                }, 0)
            });
    })
    
  • 0

    你可以过去

    el.get(0).getLocality()
    

相关问题