Thursday 23 February 2017

Google-API places autocomplete in jQuery

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.

<script src="" 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. 
Html code:
<html xmlns="">
    <title>Google Places Autocomplete textbox using google maps api</title>
<body style="border: 1px solid #DED8D8; width: 500px; height: 325px;">
    <h2> Get address from google maps API</h2>
    <script src=""></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>: " + + "<br/>";
                location += "<b>Longitude</b>: " + place.geometry.location.lng();
                document.getElementById('lblResult').innerHTML =location
    <input type="text" id="txtAutocomplete" style="width: 300px" placeholder="Enter youraddress" /><br />
    <br />
    <label id="lblResult" />

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), (Latitude value) and geometry.location.lng() (Longitude value)  respectively using google maps API v3.