更改 Google 地图自动完成字段的值

use*_*531 9 javascript jquery google-maps google-maps-api-3 google-maps-autocomplete

更改值后,如何更改 Google 地图自动完成字段的值?

我的最终愿望是只在该字段中显示地址,在不同的字段中显示城市、州等。

正如http://jsbin.com/wiye/2/(下面复制的脚本)所见,我更改了值,但后来又改回来了。

show just the street address in google.maps.event.addListener()提出了同样的问题,但它似乎不再起作用。 Change the value in textbox of a google map autocomplete也会问同样的问题,但没有足够的答案。

谢谢

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Places search box</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js" type="text/javascript"></script>
        <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
        <script>
            $(function(){
                var input_auto = document.getElementById('input_auto');
                autocomplete = new google.maps.places.Autocomplete(input_auto,{types: ['geocode'],radius: 10});
                google.maps.event.addListener(autocomplete, 'place_changed', function() {
                    setTimeout(function(){$('#input_auto').val('yyy');},50);
                    alert('pause1');
                    console.log(autocomplete,input_auto);
                    input_auto.value='xxx';
                    //autocomplete.set('xxx');
                    //autocomplete.setValues('xxx');
                    alert('pause2');
                });
            });

        </script>
    </head>
    <body>
        <input id="input_auto" type="text">
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

Nic*_*ers -2

您可以通过添加事件侦听器blurkeydown事件来覆盖自动值来解决此问题。看看我在下面做了什么:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Places search box</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js" type="text/javascript"></script>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
    <script>
      $(function(){
        var input_auto = document.getElementById('input_auto');
        autocomplete = new google.maps.places.Autocomplete(input_auto,{types: ['geocode'],radius: 10});
        google.maps.event.addListener(autocomplete, 'place_changed', function() {
          input_auto.addEventListener('blur', function() {
            input_auto.value = 'yyy';
          });
          input_auto.addEventListener('keydown', function() {
            input_auto.value = 'yyy';
          });
          setTimeout(function(){$('#input_auto').val('yyy');},1);
        });
      });

    </script>
  </head>
  <body>
    <input id="input_auto" type="text">
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

如果遇到任何问题,您可以选择添加 setTimeouts。