簡體   English   中英

如何在我的地理位置 HTML 表單中添加自動填充?

[英]How can I add Autofill in my geo location HTML Form?

我想在我的按鈕中添加自動填充功能,以便用戶開始編寫位置名稱時,它應該使用谷歌庫建議名稱。 目前我正在接受用戶的完整輸入並點擊一個按鈕來顯示經度和緯度,如果位置名稱很長,這將是不准確的。

</head>
<!-- To use Geocoding from Google Maps V3 you need to link https://maps.googleapis.com/maps/api/js?sensor=false -->
<body>
<div>
     <h3> Enter an adress and press the button</h3>

    <input id="address"  type="text" placeholder="Enter address here" />
    <button id="btn">Get LatLong</button>
    <div>
        <p>Latitude:
            <input type="text" id="latitude" readonly />
        </p>
        <p>Longitude:
            <input type="text" id="longitude" readonly />
        </p>
    </div>
</div>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">

    /* This showResult function is used as the callback function*/

function showResult(result) {
    document.getElementById('latitude').value = result.geometry.location.lat();
    document.getElementById('longitude').value = result.geometry.location.lng();
}

function getLatitudeLongitude(callback, address) {
    // If adress is not supplied, use default value 'Ferrol, Galicia, Spain'
    address = address || 'Ferrol, Galicia, Spain';
    // Initialize the Geocoder
    geocoder = new google.maps.Geocoder();
    if (geocoder) {
        geocoder.geocode({
            'address': address
        }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                callback(results[0]);
            }
        });
    }
}

var button = document.getElementById('btn');

button.addEventListener("click", function () {
    var address = document.getElementById('address').value;
    getLatitudeLongitude(showResult, address)
});
var addressbutton = document.getElementById('address');

addressbutton.addEventListener("keydown", function (e) {
    if (e.keyCode === 13) { 
        var address = document.getElementById('address').value;
    getLatitudeLongitude(showResult, address)
    }
});
</script>
</body>
</html>

Google Maps API 有一個自動完成方法new google.maps.places.Autocomplete(input); . 該方法將為您完成所有繁重的工作,它將根據輸入的位置顯示結果。

您應該使用document.getElementById('latitude')獲取輸入。

在您的情況下,它應該如下所示:

var input = document.getElementById('latitude')
var autocomplete = new google.maps.places.Autocomplete(input);

谷歌提供了一些示例代碼

自動完成類的文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM