我想在我的按钮中添加自动填充编写位置的名称,应该使用Google库建议名称。目前,我正在获取用户的全部输入并点击按钮以显示经度和纬度,如果位置的名称长。
不准确。</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);
Google提供一些示例代码
自动完成类的文档