繁体   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