Google Map Autocomplete Address

Here is the complete code to add google map autocomplete search box.

Generate Google key from the following URL :

Note:Replace googlekey in the below code with your genrated one

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
    <style type="text/css">
            font-family: Arial;
            font-size: 10pt;
    <script type="text/javascript" src=""></script>
    <script type="text/javascript">
        google.maps.event.addDomListener(window, 'load', function () {
            var places = new google.maps.places.Autocomplete(document.getElementById('txtPlaces'), {types: ['address'], componentRestrictions: {country: ['us','can']}});
            google.maps.event.addListener(places, 'place_changed', function () {
                var place = places.getPlace();
                var postalcode='';
                for (var i = 0; i < place.address_components.length; i++) {
                for (var j = 0; j < place.address_components[i].types.length; j++) {
                    if (place.address_components[i].types[j] == "postal_code") {
                    postalcode = place.address_components[i].long_name;

                var address = place.formatted_address;
    <input type="text" id="txtPlaces" style="width: 250px" placeholder="Enter a location" />

Ensuring that only Google Maps adresses are inputted

<script type="text/javascript">
  var googleaddressSelected='0';
  var txtval=$("#txtPlaces").val();
    $("#txtPlaces").on("focus", function(){ //if anything in input is changed
      googleaddressSelected='0'; //set googleaddressSelected to false
      txtval=$(this).val(); //get calue to compare on focus out
      $(document).on('click','.pac-item',function(){ //if autocomplete is clicked (pac-item is the row class returned by autocomplete)
      googleaddressSelected='1'; // if address is selected from autocomplete then set googleaddressSelected to true



    $(document).on('focusout','#txtPlaces',function () {
      var txtval2=$(this).val();
      if(googleaddressSelected=='0' && txtval2!=txtval){ //if address is not selected from autocomplete and text box value is changed
      console.log("address not picked by google map");

<!-- google autocomplete script ends here -->