I want to add autofill in my button so as soon as the user starts writing the name of the location, it should suggest the name using google library. Currently I am taking the full input from user and hitting a button to show the longitude and latitude which is not accurate if the name of location is long.
</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 has an autocomplete method new google.maps.places.Autocomplete(input);
. The method will do all the hard work for you, it will display results depending on the location entered.
You should get the input by using document.getElementById('latitude')
.
In your situation it should look like this:
var input = document.getElementById('latitude')
var autocomplete = new google.maps.places.Autocomplete(input);
Google provide some example code
The documentation for the autocomplete class
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.