I am currently using Google's address autocomplete api to get the locations (address) as shown in example here
https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform
Now I would like to get only Latitude and longitude of address, when user selects the address.
How can I do this using Javascript or jQuery?
To get latitude and longitude using Google maps api and Javascript, use the below code with scripts
<script src="http://maps.googleapis.com/maps/api/js?Key=APIKey&libraries=places" type="text/javascript"></script>
<script type="text/javascript">
function initialize() {
var input = document.getElementById('SearchTerm');
var autocomplete = new google.maps.places.Autocomplete(input);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var place = autocomplete.getPlace();
// get lat/long using place.geometry.location
document.getElementById('latitude').value = place.geometry.location.lat();
document.getElementById('longitude').value = place.geometry.location.lng();
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Considering your HTML as below
<input id="SearchTerm" type="text" placeholder="Enter a location to get lat/long" autocomplete="on" /> <br/>
Lat : <input type="text" id="latitude" name="latitude" /> <br/>
Long : <input type="text" id="longitude" name="longitude" /> <br/>
Do not forget to replace APIKey with your google api key to make it work.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly