有没有更好的方法来使用2个自动填充地址字段

时间:2019-06-16 08:28:52

标签: javascript html

我正在使用以下代码自动查找街道名称,但是

  1. 它似乎不太有效,并且
  2. 当同一页面上有2个搜索字段时-它起作用 间歇地。

试图更改表单名称和脚本变量。

<input id="autocomplete_search"  name="addressA" type="text"/>
<input type="hidden" name="lat"/>
<input type="hidden" name="long"/>


<input id="autocomplete_searchB" name="addressB" type="text"/>
<input type="hidden" name="latB"/>
<input type="hidden" name="longB"/>

<script type="text/javascript" 
src="https://maps.googleapis.com/maps/api/js?    
key=MYKEY&amp;libraries=places"></script>

<script>
    google.maps.event.addDomListener(window, 'load', initialize);
    function initialize() {
        var input = document.getElementById('autocomplete_search');
        var autocomplete = new google.maps.places.Autocomplete(input);
        autocomplete.addListener('place_changed', function () {
            var place = autocomplete.getPlace();
            // place variable will have all the information you are looking for.
            $('#lat').val(place.geometry['location'].lat());
            $('#long').val(place.geometry['location'].lng());
        });
    }
</script>

<script>
    google.maps.event.addDomListener(window, 'load', initialize);

    function initialize() {
        var inputB = document.getElementById('autocomplete_searchB');
        var autocompleteB = new google.maps.places.Autocomplete(inputB);
        autocompleteB.addListener('place_changed', function () {
            var placeB = autocomplete.getPlace();

            // place variable will have all the information you are looking for.
            $('#latB').val(placeB.geometry['location'].lat());
            $('#longB').val(placeB.geometry['location'].lng());
        });
    }
</script>

需要2个自动完成搜索字段,它们可以在同一页面上找到有效的街道名称。

1 个答案:

答案 0 :(得分:0)

您可以使用数据列表进行自动补全

<input list="autocomplete_search"  name="addressA" type="text"/>
<datalist id="autocomplete_search">
<option value="address1">
<option value="address2">
</datalist>

<input list="autocomplete_searchB"  name="addressA" type="text"/>
<datalist id="autocomplete_searchB">
<option value="address1">
<option value="address2">
</datalist>