Wednesday, 22 June 2016

Apply google address autocomplete on multiple input text boxes.

Sometimes we need to implement the autocomplete on multiple address controls like AddressLine1 and AddressLine2. For handle such type of case we can use the following code.

First of all include following library in html file;
<script src="https://maps.googleapis.com/maps/api/js?key=xxxx&signed_in=true&libraries=places"></script>

 var address = initAutocomplete("inputAddress", fillAddress);//Initializing autocomplete for address1
 var address2 = initAutocomplete("inputAddress2", fillAddress2);//Initializing autocomplete for address2.

//This is the common function that binds the auto complete with passed input controls. Callback functions fires evertime when we select address from the address dropdown.
 function initAutocomplete(elementId, callback) {
          var autocomplete = new google.maps.places.Autocomplete((document.getElementById(elementId)));
          autocomplete.addListener('place_changed', callback);
          return autocomplete;
 }

//this function is responsible for get address location longitude and latitude for address1.
function fillAddress1() {
        var place = address.getPlace();
        var addressLocationLngLat = place.geometry.location.lng() + "," + place.geometry.location.lat();
        var adddressString = $("#inputAddress").val();
}

//this function is responsible for get address location longitude and latitude for address2.
function fillAddress2() {
        var place = address2.getPlace();
        var addressLocationLngLat = place.geometry.location.lng() + "," + place.geometry.location.lat();
        var adddressString = $("#inputAddress").val();
}

No comments:

Post a Comment