In this article, I will show you how to get address from google maps places autocomplete using jQuery. If a user searches a city or country name in textbox it automatically gets the Address, Longitude and Latitude value.
To get started working with google maps location API click the link which will guide you the process of activating it.
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places&key=YOUR-KEY" type="text/javascript"></script>
The URL contained in the script tag of the source will load all the symbols and definition of the goolge maps API. You need to pass the parameter API key to the URL. To know more about google maps api click here.
Html code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Google Places Autocomplete textbox using google maps api</title>
</head>
<body style="border: 1px solid #DED8D8; width: 500px; height: 325px;">
<h2> Get address from google maps API</h2>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places&key=AIzaSyBRdtF6wK0hiNKlvpe92fT67mNg2Z9Ae5M"></script>
<script type="text/javascript">
google.maps.event.addDomListener(window, 'load', initialize);
function initialize() {
var autocomplete = new google.maps.places.Autocomplete(document.getElementById('txtAutocomplete'));
google.maps.event.addListener(autocomplete, 'place_changed', function () {
// Get the place details from the autocomplete object.
var place = autocomplete.getPlace();
var location = "<b>Address</b>:" + place.formatted_address + "<br/>";
location += "<b>Latitude</b>: " + place.geometry.location.lat() + "<br/>";
location += "<b>Longitude</b>: " + place.geometry.location.lng();
document.getElementById('lblResult').innerHTML =location
});
}
</script>
<span>Location:</span>
<input type="text" id="txtAutocomplete" style="width: 300px" placeholder="Enter youraddress" /><br />
<br />
<label id="lblResult" />
</body>
Description: When the user selects the country or city from the autocomplete textbox, jQuery event fires and gets the details from autocomplete object. From the object you can get; formatted_address (city address), geometry.location.lat() (Latitude value) and geometry.location.lng() (Longitude value) respectively using google maps API v3.