Step 1 : Create an HTML file and write the following code.
- <div class="row">
- <form role="form">
- <div class="form-group">
- <label for="email">Full Address:</label>
- <input type="text" id="FullAddress" class="form-control" />
- </div>
- <div class="form-group">
- <label for="email">Country Name:</label>
- <input type="text" id="CountryName" class="form-control" />
- </div>
- <div class="form-group">
- <label for="email">State Name:</label>
- <input type="text" id="StateName" class="form-control" />
- </div>
- <div class="form-group">
- <label for="email">City Name:</label>
- <input type="text" id="CityName" class="form-control" />
- </div>
- <div class="form-group">
- <label for="email">Zipcode:</label>
- <input type="text" id="Zipcode" class="form-control" />
- </div>
- <button type="submit" class="btn btn-default">Submit</button>
- </form>
- </div>
Step 2: Add Google places API reference in your page.
- <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
Step 3 : Next put this JavaScript code inside the head tag.
- <script type="text/javascript">
- var placeSearch, autocomplete;
-
- var addressForm = {
- CityName: 'locality',
- StateName: 'administrative_area_level_1',
- CountryName: 'country',
- Zipcode: 'postal_code'
- };
- var componentForm = {
- locality: 'long_name',
- administrative_area_level_1: 'long_name',
- country: 'long_name',
- postal_code: 'short_name'
- };
-
- initAutocomplete();
- function initAutocomplete() {
- debugger;
- autocomplete = new google.maps.places.Autocomplete((document.getElementById('FullAddress')),
- { types: ['geocode'] });
- autocomplete.addListener('place_changed', fillInAddress);
- }
-
- function fillInAddress() {
- var place = autocomplete.getPlace();
- hfLatitude.val(place.geometry.location.lat());
- hfLongitude.val(place.geometry.location.lng());
-
- for (var component in addressForm) {
- document.getElementById(component).value = '';
- document.getElementById(component).disabled = false;
- }
- for (var i = 0; i < place.address_components.length; i++) {
- var addressType = place.address_components[i].types[0];
- if (componentForm[addressType]) {
- var val = place.address_components[i][componentForm[addressType]];
- document.getElementById(getComponentKey(addressType)).value = val;
- }
- }
- }
- function getComponentKey(val) {
- for (var key in addressForm) {
- this_val = addressForm[key];
- if (this_val == val) {
- return key;
- break;
- }
- }
- }
- </script>