Google Maps API autocomplete 2nd address fields on same page












6















I am using the Google Maps API on my page, the page asks the user to fill out your "Current Address" and the "New Address".



I can get the autocomplete to work on the 1st address but it does not work for the second address, I have done lots of research and looked at simular posts on stackoverflow but I cannot find anyone who has had the same problem.



Here is my code;



<div id="locationField">
<input id="autocomplete" placeholder="Start typing your address" onFocus="geolocate()" type="text"></input>
</div>

<div id="addressone">
<input type="text" id="street_number" name="street_number"></input>
<input type="text" id="route" name="street_name"></input>
<input type="text" id="locality" name="town_city"></input>
<input type="text" id="postal_code" name="postcode"></input>
<input type="text" id="country" name="country"></input>
</div>

<div id="locationField2">
<input id="autocomplete2" placeholder="Start typing your address" onFocus="geolocate()" type="text"></input>
</div>

<div id="addresstwo">
<input type="text" id="street_number2" name="street_number2"></input>
<input type="text" id="route2" name="street_name2"></input>
<input type="text" id="locality2" name="town_city2"></input>
<input type="text" id="postal_code2" name="postcode2"></input>
<input type="text" id="country2" name="country2"></input>
</div>
<script>

// This example displays an address form, using the autocomplete feature
// of the Google Places API to help users fill in the information.

var placeSearch, autocomplete;
var componentForm = {
street_number: 'short_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'short_name',
country: 'long_name',
postal_code: 'short_name'
};

function initAutocomplete() {
// Create the autocomplete object, restricting the search to geographical
// location types.
autocomplete = new google.maps.places.Autocomplete(
/** @type {!HTMLInputElement} */(document.getElementById('autocomplete')),
{types: ['geocode']});

// When the user selects an address from the dropdown, populate the address
// fields in the form.
autocomplete.addListener('place_changed', fillInAddress);

}

// [START region_fillform]
function fillInAddress() {
// Get the place details from the autocomplete object.
var place = autocomplete.getPlace();

for (var component in componentForm) {
document.getElementById(component).value = '';
document.getElementById(component).disabled = false;
}

// Get each component of the address from the place details
// and fill the corresponding field on the form.
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(addressType).value = val;
}
}
}
// [END region_fillform]

// [START region_geolocation]
// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var geolocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var circle = new google.maps.Circle({
center: geolocation,
radius: position.coords.accuracy
});
autocomplete.setBounds(circle.getBounds());
});
}
}
// [END region_geolocation]

</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC7XIOPnu4WS_fBaIDPkCBdYa3MxdIcdK4&signed_in=true&libraries=places&callback=initAutocomplete" async defer></script>
</div>









share|improve this question

























  • You have 2 autocomplete fieldds but only code to handle the first.

    – geocodezip
    Nov 5 '15 at 14:57











  • So do I just copy and paste the js code below?

    – Brad Fletcher
    Nov 5 '15 at 15:22











  • I provided links to a couple of questions that dealt with that problem yesterday, but you seem to have deleted that version of the question, a straight copy/paste won't work. Also, the posted code doesn't work for the first form either.

    – geocodezip
    Nov 5 '15 at 15:26
















6















I am using the Google Maps API on my page, the page asks the user to fill out your "Current Address" and the "New Address".



I can get the autocomplete to work on the 1st address but it does not work for the second address, I have done lots of research and looked at simular posts on stackoverflow but I cannot find anyone who has had the same problem.



Here is my code;



<div id="locationField">
<input id="autocomplete" placeholder="Start typing your address" onFocus="geolocate()" type="text"></input>
</div>

<div id="addressone">
<input type="text" id="street_number" name="street_number"></input>
<input type="text" id="route" name="street_name"></input>
<input type="text" id="locality" name="town_city"></input>
<input type="text" id="postal_code" name="postcode"></input>
<input type="text" id="country" name="country"></input>
</div>

<div id="locationField2">
<input id="autocomplete2" placeholder="Start typing your address" onFocus="geolocate()" type="text"></input>
</div>

<div id="addresstwo">
<input type="text" id="street_number2" name="street_number2"></input>
<input type="text" id="route2" name="street_name2"></input>
<input type="text" id="locality2" name="town_city2"></input>
<input type="text" id="postal_code2" name="postcode2"></input>
<input type="text" id="country2" name="country2"></input>
</div>
<script>

// This example displays an address form, using the autocomplete feature
// of the Google Places API to help users fill in the information.

var placeSearch, autocomplete;
var componentForm = {
street_number: 'short_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'short_name',
country: 'long_name',
postal_code: 'short_name'
};

function initAutocomplete() {
// Create the autocomplete object, restricting the search to geographical
// location types.
autocomplete = new google.maps.places.Autocomplete(
/** @type {!HTMLInputElement} */(document.getElementById('autocomplete')),
{types: ['geocode']});

// When the user selects an address from the dropdown, populate the address
// fields in the form.
autocomplete.addListener('place_changed', fillInAddress);

}

// [START region_fillform]
function fillInAddress() {
// Get the place details from the autocomplete object.
var place = autocomplete.getPlace();

for (var component in componentForm) {
document.getElementById(component).value = '';
document.getElementById(component).disabled = false;
}

// Get each component of the address from the place details
// and fill the corresponding field on the form.
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(addressType).value = val;
}
}
}
// [END region_fillform]

// [START region_geolocation]
// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var geolocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var circle = new google.maps.Circle({
center: geolocation,
radius: position.coords.accuracy
});
autocomplete.setBounds(circle.getBounds());
});
}
}
// [END region_geolocation]

</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC7XIOPnu4WS_fBaIDPkCBdYa3MxdIcdK4&signed_in=true&libraries=places&callback=initAutocomplete" async defer></script>
</div>









share|improve this question

























  • You have 2 autocomplete fieldds but only code to handle the first.

    – geocodezip
    Nov 5 '15 at 14:57











  • So do I just copy and paste the js code below?

    – Brad Fletcher
    Nov 5 '15 at 15:22











  • I provided links to a couple of questions that dealt with that problem yesterday, but you seem to have deleted that version of the question, a straight copy/paste won't work. Also, the posted code doesn't work for the first form either.

    – geocodezip
    Nov 5 '15 at 15:26














6












6








6


3






I am using the Google Maps API on my page, the page asks the user to fill out your "Current Address" and the "New Address".



I can get the autocomplete to work on the 1st address but it does not work for the second address, I have done lots of research and looked at simular posts on stackoverflow but I cannot find anyone who has had the same problem.



Here is my code;



<div id="locationField">
<input id="autocomplete" placeholder="Start typing your address" onFocus="geolocate()" type="text"></input>
</div>

<div id="addressone">
<input type="text" id="street_number" name="street_number"></input>
<input type="text" id="route" name="street_name"></input>
<input type="text" id="locality" name="town_city"></input>
<input type="text" id="postal_code" name="postcode"></input>
<input type="text" id="country" name="country"></input>
</div>

<div id="locationField2">
<input id="autocomplete2" placeholder="Start typing your address" onFocus="geolocate()" type="text"></input>
</div>

<div id="addresstwo">
<input type="text" id="street_number2" name="street_number2"></input>
<input type="text" id="route2" name="street_name2"></input>
<input type="text" id="locality2" name="town_city2"></input>
<input type="text" id="postal_code2" name="postcode2"></input>
<input type="text" id="country2" name="country2"></input>
</div>
<script>

// This example displays an address form, using the autocomplete feature
// of the Google Places API to help users fill in the information.

var placeSearch, autocomplete;
var componentForm = {
street_number: 'short_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'short_name',
country: 'long_name',
postal_code: 'short_name'
};

function initAutocomplete() {
// Create the autocomplete object, restricting the search to geographical
// location types.
autocomplete = new google.maps.places.Autocomplete(
/** @type {!HTMLInputElement} */(document.getElementById('autocomplete')),
{types: ['geocode']});

// When the user selects an address from the dropdown, populate the address
// fields in the form.
autocomplete.addListener('place_changed', fillInAddress);

}

// [START region_fillform]
function fillInAddress() {
// Get the place details from the autocomplete object.
var place = autocomplete.getPlace();

for (var component in componentForm) {
document.getElementById(component).value = '';
document.getElementById(component).disabled = false;
}

// Get each component of the address from the place details
// and fill the corresponding field on the form.
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(addressType).value = val;
}
}
}
// [END region_fillform]

// [START region_geolocation]
// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var geolocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var circle = new google.maps.Circle({
center: geolocation,
radius: position.coords.accuracy
});
autocomplete.setBounds(circle.getBounds());
});
}
}
// [END region_geolocation]

</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC7XIOPnu4WS_fBaIDPkCBdYa3MxdIcdK4&signed_in=true&libraries=places&callback=initAutocomplete" async defer></script>
</div>









share|improve this question
















I am using the Google Maps API on my page, the page asks the user to fill out your "Current Address" and the "New Address".



I can get the autocomplete to work on the 1st address but it does not work for the second address, I have done lots of research and looked at simular posts on stackoverflow but I cannot find anyone who has had the same problem.



Here is my code;



<div id="locationField">
<input id="autocomplete" placeholder="Start typing your address" onFocus="geolocate()" type="text"></input>
</div>

<div id="addressone">
<input type="text" id="street_number" name="street_number"></input>
<input type="text" id="route" name="street_name"></input>
<input type="text" id="locality" name="town_city"></input>
<input type="text" id="postal_code" name="postcode"></input>
<input type="text" id="country" name="country"></input>
</div>

<div id="locationField2">
<input id="autocomplete2" placeholder="Start typing your address" onFocus="geolocate()" type="text"></input>
</div>

<div id="addresstwo">
<input type="text" id="street_number2" name="street_number2"></input>
<input type="text" id="route2" name="street_name2"></input>
<input type="text" id="locality2" name="town_city2"></input>
<input type="text" id="postal_code2" name="postcode2"></input>
<input type="text" id="country2" name="country2"></input>
</div>
<script>

// This example displays an address form, using the autocomplete feature
// of the Google Places API to help users fill in the information.

var placeSearch, autocomplete;
var componentForm = {
street_number: 'short_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'short_name',
country: 'long_name',
postal_code: 'short_name'
};

function initAutocomplete() {
// Create the autocomplete object, restricting the search to geographical
// location types.
autocomplete = new google.maps.places.Autocomplete(
/** @type {!HTMLInputElement} */(document.getElementById('autocomplete')),
{types: ['geocode']});

// When the user selects an address from the dropdown, populate the address
// fields in the form.
autocomplete.addListener('place_changed', fillInAddress);

}

// [START region_fillform]
function fillInAddress() {
// Get the place details from the autocomplete object.
var place = autocomplete.getPlace();

for (var component in componentForm) {
document.getElementById(component).value = '';
document.getElementById(component).disabled = false;
}

// Get each component of the address from the place details
// and fill the corresponding field on the form.
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(addressType).value = val;
}
}
}
// [END region_fillform]

// [START region_geolocation]
// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var geolocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var circle = new google.maps.Circle({
center: geolocation,
radius: position.coords.accuracy
});
autocomplete.setBounds(circle.getBounds());
});
}
}
// [END region_geolocation]

</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC7XIOPnu4WS_fBaIDPkCBdYa3MxdIcdK4&signed_in=true&libraries=places&callback=initAutocomplete" async defer></script>
</div>






javascript google-maps google-maps-api-3






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 5 '15 at 14:43









geocodezip

125k10142172




125k10142172










asked Nov 5 '15 at 14:36









Brad FletcherBrad Fletcher

1,77821432




1,77821432













  • You have 2 autocomplete fieldds but only code to handle the first.

    – geocodezip
    Nov 5 '15 at 14:57











  • So do I just copy and paste the js code below?

    – Brad Fletcher
    Nov 5 '15 at 15:22











  • I provided links to a couple of questions that dealt with that problem yesterday, but you seem to have deleted that version of the question, a straight copy/paste won't work. Also, the posted code doesn't work for the first form either.

    – geocodezip
    Nov 5 '15 at 15:26



















  • You have 2 autocomplete fieldds but only code to handle the first.

    – geocodezip
    Nov 5 '15 at 14:57











  • So do I just copy and paste the js code below?

    – Brad Fletcher
    Nov 5 '15 at 15:22











  • I provided links to a couple of questions that dealt with that problem yesterday, but you seem to have deleted that version of the question, a straight copy/paste won't work. Also, the posted code doesn't work for the first form either.

    – geocodezip
    Nov 5 '15 at 15:26

















You have 2 autocomplete fieldds but only code to handle the first.

– geocodezip
Nov 5 '15 at 14:57





You have 2 autocomplete fieldds but only code to handle the first.

– geocodezip
Nov 5 '15 at 14:57













So do I just copy and paste the js code below?

– Brad Fletcher
Nov 5 '15 at 15:22





So do I just copy and paste the js code below?

– Brad Fletcher
Nov 5 '15 at 15:22













I provided links to a couple of questions that dealt with that problem yesterday, but you seem to have deleted that version of the question, a straight copy/paste won't work. Also, the posted code doesn't work for the first form either.

– geocodezip
Nov 5 '15 at 15:26





I provided links to a couple of questions that dealt with that problem yesterday, but you seem to have deleted that version of the question, a straight copy/paste won't work. Also, the posted code doesn't work for the first form either.

– geocodezip
Nov 5 '15 at 15:26












3 Answers
3






active

oldest

votes


















13














You need to hande the two autocomplete inputs. Here is a generalized version of fillInAddress that will handle multiple autocomplete objects with fields with a unique extension (the "2" in your second version of the form):



function fillInAddress(autocomplete, unique) {
// Get the place details from the autocomplete object.
var place = autocomplete.getPlace();

for (var component in componentForm) {
if(!!document.getElementById(component + unique)){
document.getElementById(component + unique).value = '';
document.getElementById(component + unique).disabled = false;
}
}

// Get each component of the address from the place details
// and fill the corresponding field on the form.
for (var i = 0; i < place.address_components.length; i++) {
var addressType = place.address_components[i].types[0];
if (componentForm[addressType] && document.getElementById(addressType + unique)) {
var val = place.address_components[i][componentForm[addressType]];
document.getElementById(addressType + unique).value = val;
}
}
}


Call it like this:



// Create the autocomplete object, restricting the search to geographical
// location types.
autocomplete = new google.maps.places.Autocomplete(
/** @type {!HTMLInputElement} */
(document.getElementById('autocomplete')), {
types: ['geocode']
});

// When the user selects an address from the dropdown, populate the address
// fields in the form.
autocomplete.addListener('place_changed', function () {
fillInAddress(autocomplete, "");
});

// Create the second autocomplete object, restricting the search to geographical
// location types.
autocomplete2 = new google.maps.places.Autocomplete(
/** @type {!HTMLInputElement} */
(document.getElementById('autocomplete2')), {
types: ['geocode']
});
autocomplete2.addListener('place_changed', function () {
fillInAddress(autocomplete2, "2");
});


working code snippet:






// This example displays an address form, using the autocomplete feature
// of the Google Places API to help users fill in the information.

var placeSearch, autocomplete, autocomplete2;
var componentForm = {
street_number: 'short_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'short_name',
country: 'long_name',
postal_code: 'short_name'
};

function initAutocomplete() {
// Create the autocomplete object, restricting the search to geographical
// location types.
autocomplete = new google.maps.places.Autocomplete(
/** @type {!HTMLInputElement} */
(document.getElementById('autocomplete')), {
types: ['geocode']
});

// When the user selects an address from the dropdown, populate the address
// fields in the form.
autocomplete.addListener('place_changed', function() {
fillInAddress(autocomplete, "");
});

autocomplete2 = new google.maps.places.Autocomplete(
/** @type {!HTMLInputElement} */
(document.getElementById('autocomplete2')), {
types: ['geocode']
});
autocomplete2.addListener('place_changed', function() {
fillInAddress(autocomplete2, "2");
});

}

function fillInAddress(autocomplete, unique) {
// Get the place details from the autocomplete object.
var place = autocomplete.getPlace();

for (var component in componentForm) {
if (!!document.getElementById(component + unique)) {
document.getElementById(component + unique).value = '';
document.getElementById(component + unique).disabled = false;
}
}

// Get each component of the address from the place details
// and fill the corresponding field on the form.
for (var i = 0; i < place.address_components.length; i++) {
var addressType = place.address_components[i].types[0];
if (componentForm[addressType] && document.getElementById(addressType + unique)) {
var val = place.address_components[i][componentForm[addressType]];
document.getElementById(addressType + unique).value = val;
}
}
}
google.maps.event.addDomListener(window, "load", initAutocomplete);

function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var geolocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var circle = new google.maps.Circle({
center: geolocation,
radius: position.coords.accuracy
});
autocomplete.setBounds(circle.getBounds());
});
}
}

<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<div id="locationField">
<input id="autocomplete" placeholder="Start typing your address" onFocus="geolocate()" type="text" />
</div>
<div id="addressone">
<input type="text" id="street_number" name="street_number" />
<input type="text" id="route" name="street_name" />
<input type="text" id="locality" name="town_city" />
<input type="text" id="administrative_area_level_1" name="administrative_area_level_1" />
<input type="text" id="postal_code" name="postcode" />
<input type="text" id="country" name="country" />
</div>
<div id="locationField2">
<input id="autocomplete2" placeholder="Start typing your address" onFocus="geolocate()" type="text" />
</div>
<div id="addresstwo">
<input type="text" id="street_number2" name="street_number2" />
<input type="text" id="route2" name="street_name2" />
<input type="text" id="locality2" name="town_city2" />
<input type="text" id="administrative_area_level_12" name="administrative_area_level_12" />
<input type="text" id="postal_code2" name="postcode2" />
<input type="text" id="country2" name="country2" />
</div>








share|improve this answer

































    1














    This works like a charm :)



    thanks jQuery.



    function initMultiComplete() {
    jQuery('.maps-complete').each(function(){

    var id = jQuery(this).prop('id');
    var $this = jQuery(this);
    var parent = jQuery(this).parent('div');

    var jautocomplete = new google.maps.places.Autocomplete(document.getElementById(id), {types: ['geocode']});

    jautocomplete.addListener('place_changed', function () {

    var place = jautocomplete.getPlace();
    var address = $this.val();
    var lat = place.geometry.location.lat();
    var lng = place.geometry.location.lng();

    jQuery( '.maps-autocomplete-lat', parent ).val(lat);
    jQuery( '.maps-autocomplete-lng', parent ).val(lng);

    });

    });
    }


    script calls initMultiComplete as callback, and is loaded w/ async defer:



    https://maps.googleapis.com/maps/api/js?key=YOUR_KEY&libraries=places&callback=initMultiComplete





    share|improve this answer

































      0














      This is an old question but I thought I'd post my solution to this in case it's helpful to others in the future. My solution handles any number of maps api autocomplete fields on a page. You'd need tag all autocomplete fields with a class name, in my case I've used the class name "address".



      Now grab the collection of fields:



      var input = document.getElementsByClassName('address');

      for (var x = 0; x < input.length; x++) {
      addListener(input[x]);
      }


      which calls a function called "addListener"



      function addListener(el) {
      var autocomplete = new google.maps.places.Autocomplete(el);

      google.maps.event.addListener(autocomplete, 'place_changed', function () {
      // Do whatever you want in here e.g.
      // var place = autocomplete.getPlace();
      });
      }


      Because it's a collection, you should be able to add any number of autocomplete fields to a page. Though naturally, you should check for undefined on the collection just in case you happen to have no autocomplete fields on the page.






      share|improve this answer























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f33547312%2fgoogle-maps-api-autocomplete-2nd-address-fields-on-same-page%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        13














        You need to hande the two autocomplete inputs. Here is a generalized version of fillInAddress that will handle multiple autocomplete objects with fields with a unique extension (the "2" in your second version of the form):



        function fillInAddress(autocomplete, unique) {
        // Get the place details from the autocomplete object.
        var place = autocomplete.getPlace();

        for (var component in componentForm) {
        if(!!document.getElementById(component + unique)){
        document.getElementById(component + unique).value = '';
        document.getElementById(component + unique).disabled = false;
        }
        }

        // Get each component of the address from the place details
        // and fill the corresponding field on the form.
        for (var i = 0; i < place.address_components.length; i++) {
        var addressType = place.address_components[i].types[0];
        if (componentForm[addressType] && document.getElementById(addressType + unique)) {
        var val = place.address_components[i][componentForm[addressType]];
        document.getElementById(addressType + unique).value = val;
        }
        }
        }


        Call it like this:



        // Create the autocomplete object, restricting the search to geographical
        // location types.
        autocomplete = new google.maps.places.Autocomplete(
        /** @type {!HTMLInputElement} */
        (document.getElementById('autocomplete')), {
        types: ['geocode']
        });

        // When the user selects an address from the dropdown, populate the address
        // fields in the form.
        autocomplete.addListener('place_changed', function () {
        fillInAddress(autocomplete, "");
        });

        // Create the second autocomplete object, restricting the search to geographical
        // location types.
        autocomplete2 = new google.maps.places.Autocomplete(
        /** @type {!HTMLInputElement} */
        (document.getElementById('autocomplete2')), {
        types: ['geocode']
        });
        autocomplete2.addListener('place_changed', function () {
        fillInAddress(autocomplete2, "2");
        });


        working code snippet:






        // This example displays an address form, using the autocomplete feature
        // of the Google Places API to help users fill in the information.

        var placeSearch, autocomplete, autocomplete2;
        var componentForm = {
        street_number: 'short_name',
        route: 'long_name',
        locality: 'long_name',
        administrative_area_level_1: 'short_name',
        country: 'long_name',
        postal_code: 'short_name'
        };

        function initAutocomplete() {
        // Create the autocomplete object, restricting the search to geographical
        // location types.
        autocomplete = new google.maps.places.Autocomplete(
        /** @type {!HTMLInputElement} */
        (document.getElementById('autocomplete')), {
        types: ['geocode']
        });

        // When the user selects an address from the dropdown, populate the address
        // fields in the form.
        autocomplete.addListener('place_changed', function() {
        fillInAddress(autocomplete, "");
        });

        autocomplete2 = new google.maps.places.Autocomplete(
        /** @type {!HTMLInputElement} */
        (document.getElementById('autocomplete2')), {
        types: ['geocode']
        });
        autocomplete2.addListener('place_changed', function() {
        fillInAddress(autocomplete2, "2");
        });

        }

        function fillInAddress(autocomplete, unique) {
        // Get the place details from the autocomplete object.
        var place = autocomplete.getPlace();

        for (var component in componentForm) {
        if (!!document.getElementById(component + unique)) {
        document.getElementById(component + unique).value = '';
        document.getElementById(component + unique).disabled = false;
        }
        }

        // Get each component of the address from the place details
        // and fill the corresponding field on the form.
        for (var i = 0; i < place.address_components.length; i++) {
        var addressType = place.address_components[i].types[0];
        if (componentForm[addressType] && document.getElementById(addressType + unique)) {
        var val = place.address_components[i][componentForm[addressType]];
        document.getElementById(addressType + unique).value = val;
        }
        }
        }
        google.maps.event.addDomListener(window, "load", initAutocomplete);

        function geolocate() {
        if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
        var geolocation = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
        };
        var circle = new google.maps.Circle({
        center: geolocation,
        radius: position.coords.accuracy
        });
        autocomplete.setBounds(circle.getBounds());
        });
        }
        }

        <script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
        <div id="locationField">
        <input id="autocomplete" placeholder="Start typing your address" onFocus="geolocate()" type="text" />
        </div>
        <div id="addressone">
        <input type="text" id="street_number" name="street_number" />
        <input type="text" id="route" name="street_name" />
        <input type="text" id="locality" name="town_city" />
        <input type="text" id="administrative_area_level_1" name="administrative_area_level_1" />
        <input type="text" id="postal_code" name="postcode" />
        <input type="text" id="country" name="country" />
        </div>
        <div id="locationField2">
        <input id="autocomplete2" placeholder="Start typing your address" onFocus="geolocate()" type="text" />
        </div>
        <div id="addresstwo">
        <input type="text" id="street_number2" name="street_number2" />
        <input type="text" id="route2" name="street_name2" />
        <input type="text" id="locality2" name="town_city2" />
        <input type="text" id="administrative_area_level_12" name="administrative_area_level_12" />
        <input type="text" id="postal_code2" name="postcode2" />
        <input type="text" id="country2" name="country2" />
        </div>








        share|improve this answer






























          13














          You need to hande the two autocomplete inputs. Here is a generalized version of fillInAddress that will handle multiple autocomplete objects with fields with a unique extension (the "2" in your second version of the form):



          function fillInAddress(autocomplete, unique) {
          // Get the place details from the autocomplete object.
          var place = autocomplete.getPlace();

          for (var component in componentForm) {
          if(!!document.getElementById(component + unique)){
          document.getElementById(component + unique).value = '';
          document.getElementById(component + unique).disabled = false;
          }
          }

          // Get each component of the address from the place details
          // and fill the corresponding field on the form.
          for (var i = 0; i < place.address_components.length; i++) {
          var addressType = place.address_components[i].types[0];
          if (componentForm[addressType] && document.getElementById(addressType + unique)) {
          var val = place.address_components[i][componentForm[addressType]];
          document.getElementById(addressType + unique).value = val;
          }
          }
          }


          Call it like this:



          // Create the autocomplete object, restricting the search to geographical
          // location types.
          autocomplete = new google.maps.places.Autocomplete(
          /** @type {!HTMLInputElement} */
          (document.getElementById('autocomplete')), {
          types: ['geocode']
          });

          // When the user selects an address from the dropdown, populate the address
          // fields in the form.
          autocomplete.addListener('place_changed', function () {
          fillInAddress(autocomplete, "");
          });

          // Create the second autocomplete object, restricting the search to geographical
          // location types.
          autocomplete2 = new google.maps.places.Autocomplete(
          /** @type {!HTMLInputElement} */
          (document.getElementById('autocomplete2')), {
          types: ['geocode']
          });
          autocomplete2.addListener('place_changed', function () {
          fillInAddress(autocomplete2, "2");
          });


          working code snippet:






          // This example displays an address form, using the autocomplete feature
          // of the Google Places API to help users fill in the information.

          var placeSearch, autocomplete, autocomplete2;
          var componentForm = {
          street_number: 'short_name',
          route: 'long_name',
          locality: 'long_name',
          administrative_area_level_1: 'short_name',
          country: 'long_name',
          postal_code: 'short_name'
          };

          function initAutocomplete() {
          // Create the autocomplete object, restricting the search to geographical
          // location types.
          autocomplete = new google.maps.places.Autocomplete(
          /** @type {!HTMLInputElement} */
          (document.getElementById('autocomplete')), {
          types: ['geocode']
          });

          // When the user selects an address from the dropdown, populate the address
          // fields in the form.
          autocomplete.addListener('place_changed', function() {
          fillInAddress(autocomplete, "");
          });

          autocomplete2 = new google.maps.places.Autocomplete(
          /** @type {!HTMLInputElement} */
          (document.getElementById('autocomplete2')), {
          types: ['geocode']
          });
          autocomplete2.addListener('place_changed', function() {
          fillInAddress(autocomplete2, "2");
          });

          }

          function fillInAddress(autocomplete, unique) {
          // Get the place details from the autocomplete object.
          var place = autocomplete.getPlace();

          for (var component in componentForm) {
          if (!!document.getElementById(component + unique)) {
          document.getElementById(component + unique).value = '';
          document.getElementById(component + unique).disabled = false;
          }
          }

          // Get each component of the address from the place details
          // and fill the corresponding field on the form.
          for (var i = 0; i < place.address_components.length; i++) {
          var addressType = place.address_components[i].types[0];
          if (componentForm[addressType] && document.getElementById(addressType + unique)) {
          var val = place.address_components[i][componentForm[addressType]];
          document.getElementById(addressType + unique).value = val;
          }
          }
          }
          google.maps.event.addDomListener(window, "load", initAutocomplete);

          function geolocate() {
          if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(function(position) {
          var geolocation = {
          lat: position.coords.latitude,
          lng: position.coords.longitude
          };
          var circle = new google.maps.Circle({
          center: geolocation,
          radius: position.coords.accuracy
          });
          autocomplete.setBounds(circle.getBounds());
          });
          }
          }

          <script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
          <div id="locationField">
          <input id="autocomplete" placeholder="Start typing your address" onFocus="geolocate()" type="text" />
          </div>
          <div id="addressone">
          <input type="text" id="street_number" name="street_number" />
          <input type="text" id="route" name="street_name" />
          <input type="text" id="locality" name="town_city" />
          <input type="text" id="administrative_area_level_1" name="administrative_area_level_1" />
          <input type="text" id="postal_code" name="postcode" />
          <input type="text" id="country" name="country" />
          </div>
          <div id="locationField2">
          <input id="autocomplete2" placeholder="Start typing your address" onFocus="geolocate()" type="text" />
          </div>
          <div id="addresstwo">
          <input type="text" id="street_number2" name="street_number2" />
          <input type="text" id="route2" name="street_name2" />
          <input type="text" id="locality2" name="town_city2" />
          <input type="text" id="administrative_area_level_12" name="administrative_area_level_12" />
          <input type="text" id="postal_code2" name="postcode2" />
          <input type="text" id="country2" name="country2" />
          </div>








          share|improve this answer




























            13












            13








            13







            You need to hande the two autocomplete inputs. Here is a generalized version of fillInAddress that will handle multiple autocomplete objects with fields with a unique extension (the "2" in your second version of the form):



            function fillInAddress(autocomplete, unique) {
            // Get the place details from the autocomplete object.
            var place = autocomplete.getPlace();

            for (var component in componentForm) {
            if(!!document.getElementById(component + unique)){
            document.getElementById(component + unique).value = '';
            document.getElementById(component + unique).disabled = false;
            }
            }

            // Get each component of the address from the place details
            // and fill the corresponding field on the form.
            for (var i = 0; i < place.address_components.length; i++) {
            var addressType = place.address_components[i].types[0];
            if (componentForm[addressType] && document.getElementById(addressType + unique)) {
            var val = place.address_components[i][componentForm[addressType]];
            document.getElementById(addressType + unique).value = val;
            }
            }
            }


            Call it like this:



            // Create the autocomplete object, restricting the search to geographical
            // location types.
            autocomplete = new google.maps.places.Autocomplete(
            /** @type {!HTMLInputElement} */
            (document.getElementById('autocomplete')), {
            types: ['geocode']
            });

            // When the user selects an address from the dropdown, populate the address
            // fields in the form.
            autocomplete.addListener('place_changed', function () {
            fillInAddress(autocomplete, "");
            });

            // Create the second autocomplete object, restricting the search to geographical
            // location types.
            autocomplete2 = new google.maps.places.Autocomplete(
            /** @type {!HTMLInputElement} */
            (document.getElementById('autocomplete2')), {
            types: ['geocode']
            });
            autocomplete2.addListener('place_changed', function () {
            fillInAddress(autocomplete2, "2");
            });


            working code snippet:






            // This example displays an address form, using the autocomplete feature
            // of the Google Places API to help users fill in the information.

            var placeSearch, autocomplete, autocomplete2;
            var componentForm = {
            street_number: 'short_name',
            route: 'long_name',
            locality: 'long_name',
            administrative_area_level_1: 'short_name',
            country: 'long_name',
            postal_code: 'short_name'
            };

            function initAutocomplete() {
            // Create the autocomplete object, restricting the search to geographical
            // location types.
            autocomplete = new google.maps.places.Autocomplete(
            /** @type {!HTMLInputElement} */
            (document.getElementById('autocomplete')), {
            types: ['geocode']
            });

            // When the user selects an address from the dropdown, populate the address
            // fields in the form.
            autocomplete.addListener('place_changed', function() {
            fillInAddress(autocomplete, "");
            });

            autocomplete2 = new google.maps.places.Autocomplete(
            /** @type {!HTMLInputElement} */
            (document.getElementById('autocomplete2')), {
            types: ['geocode']
            });
            autocomplete2.addListener('place_changed', function() {
            fillInAddress(autocomplete2, "2");
            });

            }

            function fillInAddress(autocomplete, unique) {
            // Get the place details from the autocomplete object.
            var place = autocomplete.getPlace();

            for (var component in componentForm) {
            if (!!document.getElementById(component + unique)) {
            document.getElementById(component + unique).value = '';
            document.getElementById(component + unique).disabled = false;
            }
            }

            // Get each component of the address from the place details
            // and fill the corresponding field on the form.
            for (var i = 0; i < place.address_components.length; i++) {
            var addressType = place.address_components[i].types[0];
            if (componentForm[addressType] && document.getElementById(addressType + unique)) {
            var val = place.address_components[i][componentForm[addressType]];
            document.getElementById(addressType + unique).value = val;
            }
            }
            }
            google.maps.event.addDomListener(window, "load", initAutocomplete);

            function geolocate() {
            if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
            var geolocation = {
            lat: position.coords.latitude,
            lng: position.coords.longitude
            };
            var circle = new google.maps.Circle({
            center: geolocation,
            radius: position.coords.accuracy
            });
            autocomplete.setBounds(circle.getBounds());
            });
            }
            }

            <script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
            <div id="locationField">
            <input id="autocomplete" placeholder="Start typing your address" onFocus="geolocate()" type="text" />
            </div>
            <div id="addressone">
            <input type="text" id="street_number" name="street_number" />
            <input type="text" id="route" name="street_name" />
            <input type="text" id="locality" name="town_city" />
            <input type="text" id="administrative_area_level_1" name="administrative_area_level_1" />
            <input type="text" id="postal_code" name="postcode" />
            <input type="text" id="country" name="country" />
            </div>
            <div id="locationField2">
            <input id="autocomplete2" placeholder="Start typing your address" onFocus="geolocate()" type="text" />
            </div>
            <div id="addresstwo">
            <input type="text" id="street_number2" name="street_number2" />
            <input type="text" id="route2" name="street_name2" />
            <input type="text" id="locality2" name="town_city2" />
            <input type="text" id="administrative_area_level_12" name="administrative_area_level_12" />
            <input type="text" id="postal_code2" name="postcode2" />
            <input type="text" id="country2" name="country2" />
            </div>








            share|improve this answer















            You need to hande the two autocomplete inputs. Here is a generalized version of fillInAddress that will handle multiple autocomplete objects with fields with a unique extension (the "2" in your second version of the form):



            function fillInAddress(autocomplete, unique) {
            // Get the place details from the autocomplete object.
            var place = autocomplete.getPlace();

            for (var component in componentForm) {
            if(!!document.getElementById(component + unique)){
            document.getElementById(component + unique).value = '';
            document.getElementById(component + unique).disabled = false;
            }
            }

            // Get each component of the address from the place details
            // and fill the corresponding field on the form.
            for (var i = 0; i < place.address_components.length; i++) {
            var addressType = place.address_components[i].types[0];
            if (componentForm[addressType] && document.getElementById(addressType + unique)) {
            var val = place.address_components[i][componentForm[addressType]];
            document.getElementById(addressType + unique).value = val;
            }
            }
            }


            Call it like this:



            // Create the autocomplete object, restricting the search to geographical
            // location types.
            autocomplete = new google.maps.places.Autocomplete(
            /** @type {!HTMLInputElement} */
            (document.getElementById('autocomplete')), {
            types: ['geocode']
            });

            // When the user selects an address from the dropdown, populate the address
            // fields in the form.
            autocomplete.addListener('place_changed', function () {
            fillInAddress(autocomplete, "");
            });

            // Create the second autocomplete object, restricting the search to geographical
            // location types.
            autocomplete2 = new google.maps.places.Autocomplete(
            /** @type {!HTMLInputElement} */
            (document.getElementById('autocomplete2')), {
            types: ['geocode']
            });
            autocomplete2.addListener('place_changed', function () {
            fillInAddress(autocomplete2, "2");
            });


            working code snippet:






            // This example displays an address form, using the autocomplete feature
            // of the Google Places API to help users fill in the information.

            var placeSearch, autocomplete, autocomplete2;
            var componentForm = {
            street_number: 'short_name',
            route: 'long_name',
            locality: 'long_name',
            administrative_area_level_1: 'short_name',
            country: 'long_name',
            postal_code: 'short_name'
            };

            function initAutocomplete() {
            // Create the autocomplete object, restricting the search to geographical
            // location types.
            autocomplete = new google.maps.places.Autocomplete(
            /** @type {!HTMLInputElement} */
            (document.getElementById('autocomplete')), {
            types: ['geocode']
            });

            // When the user selects an address from the dropdown, populate the address
            // fields in the form.
            autocomplete.addListener('place_changed', function() {
            fillInAddress(autocomplete, "");
            });

            autocomplete2 = new google.maps.places.Autocomplete(
            /** @type {!HTMLInputElement} */
            (document.getElementById('autocomplete2')), {
            types: ['geocode']
            });
            autocomplete2.addListener('place_changed', function() {
            fillInAddress(autocomplete2, "2");
            });

            }

            function fillInAddress(autocomplete, unique) {
            // Get the place details from the autocomplete object.
            var place = autocomplete.getPlace();

            for (var component in componentForm) {
            if (!!document.getElementById(component + unique)) {
            document.getElementById(component + unique).value = '';
            document.getElementById(component + unique).disabled = false;
            }
            }

            // Get each component of the address from the place details
            // and fill the corresponding field on the form.
            for (var i = 0; i < place.address_components.length; i++) {
            var addressType = place.address_components[i].types[0];
            if (componentForm[addressType] && document.getElementById(addressType + unique)) {
            var val = place.address_components[i][componentForm[addressType]];
            document.getElementById(addressType + unique).value = val;
            }
            }
            }
            google.maps.event.addDomListener(window, "load", initAutocomplete);

            function geolocate() {
            if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
            var geolocation = {
            lat: position.coords.latitude,
            lng: position.coords.longitude
            };
            var circle = new google.maps.Circle({
            center: geolocation,
            radius: position.coords.accuracy
            });
            autocomplete.setBounds(circle.getBounds());
            });
            }
            }

            <script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
            <div id="locationField">
            <input id="autocomplete" placeholder="Start typing your address" onFocus="geolocate()" type="text" />
            </div>
            <div id="addressone">
            <input type="text" id="street_number" name="street_number" />
            <input type="text" id="route" name="street_name" />
            <input type="text" id="locality" name="town_city" />
            <input type="text" id="administrative_area_level_1" name="administrative_area_level_1" />
            <input type="text" id="postal_code" name="postcode" />
            <input type="text" id="country" name="country" />
            </div>
            <div id="locationField2">
            <input id="autocomplete2" placeholder="Start typing your address" onFocus="geolocate()" type="text" />
            </div>
            <div id="addresstwo">
            <input type="text" id="street_number2" name="street_number2" />
            <input type="text" id="route2" name="street_name2" />
            <input type="text" id="locality2" name="town_city2" />
            <input type="text" id="administrative_area_level_12" name="administrative_area_level_12" />
            <input type="text" id="postal_code2" name="postcode2" />
            <input type="text" id="country2" name="country2" />
            </div>








            // This example displays an address form, using the autocomplete feature
            // of the Google Places API to help users fill in the information.

            var placeSearch, autocomplete, autocomplete2;
            var componentForm = {
            street_number: 'short_name',
            route: 'long_name',
            locality: 'long_name',
            administrative_area_level_1: 'short_name',
            country: 'long_name',
            postal_code: 'short_name'
            };

            function initAutocomplete() {
            // Create the autocomplete object, restricting the search to geographical
            // location types.
            autocomplete = new google.maps.places.Autocomplete(
            /** @type {!HTMLInputElement} */
            (document.getElementById('autocomplete')), {
            types: ['geocode']
            });

            // When the user selects an address from the dropdown, populate the address
            // fields in the form.
            autocomplete.addListener('place_changed', function() {
            fillInAddress(autocomplete, "");
            });

            autocomplete2 = new google.maps.places.Autocomplete(
            /** @type {!HTMLInputElement} */
            (document.getElementById('autocomplete2')), {
            types: ['geocode']
            });
            autocomplete2.addListener('place_changed', function() {
            fillInAddress(autocomplete2, "2");
            });

            }

            function fillInAddress(autocomplete, unique) {
            // Get the place details from the autocomplete object.
            var place = autocomplete.getPlace();

            for (var component in componentForm) {
            if (!!document.getElementById(component + unique)) {
            document.getElementById(component + unique).value = '';
            document.getElementById(component + unique).disabled = false;
            }
            }

            // Get each component of the address from the place details
            // and fill the corresponding field on the form.
            for (var i = 0; i < place.address_components.length; i++) {
            var addressType = place.address_components[i].types[0];
            if (componentForm[addressType] && document.getElementById(addressType + unique)) {
            var val = place.address_components[i][componentForm[addressType]];
            document.getElementById(addressType + unique).value = val;
            }
            }
            }
            google.maps.event.addDomListener(window, "load", initAutocomplete);

            function geolocate() {
            if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
            var geolocation = {
            lat: position.coords.latitude,
            lng: position.coords.longitude
            };
            var circle = new google.maps.Circle({
            center: geolocation,
            radius: position.coords.accuracy
            });
            autocomplete.setBounds(circle.getBounds());
            });
            }
            }

            <script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
            <div id="locationField">
            <input id="autocomplete" placeholder="Start typing your address" onFocus="geolocate()" type="text" />
            </div>
            <div id="addressone">
            <input type="text" id="street_number" name="street_number" />
            <input type="text" id="route" name="street_name" />
            <input type="text" id="locality" name="town_city" />
            <input type="text" id="administrative_area_level_1" name="administrative_area_level_1" />
            <input type="text" id="postal_code" name="postcode" />
            <input type="text" id="country" name="country" />
            </div>
            <div id="locationField2">
            <input id="autocomplete2" placeholder="Start typing your address" onFocus="geolocate()" type="text" />
            </div>
            <div id="addresstwo">
            <input type="text" id="street_number2" name="street_number2" />
            <input type="text" id="route2" name="street_name2" />
            <input type="text" id="locality2" name="town_city2" />
            <input type="text" id="administrative_area_level_12" name="administrative_area_level_12" />
            <input type="text" id="postal_code2" name="postcode2" />
            <input type="text" id="country2" name="country2" />
            </div>





            // This example displays an address form, using the autocomplete feature
            // of the Google Places API to help users fill in the information.

            var placeSearch, autocomplete, autocomplete2;
            var componentForm = {
            street_number: 'short_name',
            route: 'long_name',
            locality: 'long_name',
            administrative_area_level_1: 'short_name',
            country: 'long_name',
            postal_code: 'short_name'
            };

            function initAutocomplete() {
            // Create the autocomplete object, restricting the search to geographical
            // location types.
            autocomplete = new google.maps.places.Autocomplete(
            /** @type {!HTMLInputElement} */
            (document.getElementById('autocomplete')), {
            types: ['geocode']
            });

            // When the user selects an address from the dropdown, populate the address
            // fields in the form.
            autocomplete.addListener('place_changed', function() {
            fillInAddress(autocomplete, "");
            });

            autocomplete2 = new google.maps.places.Autocomplete(
            /** @type {!HTMLInputElement} */
            (document.getElementById('autocomplete2')), {
            types: ['geocode']
            });
            autocomplete2.addListener('place_changed', function() {
            fillInAddress(autocomplete2, "2");
            });

            }

            function fillInAddress(autocomplete, unique) {
            // Get the place details from the autocomplete object.
            var place = autocomplete.getPlace();

            for (var component in componentForm) {
            if (!!document.getElementById(component + unique)) {
            document.getElementById(component + unique).value = '';
            document.getElementById(component + unique).disabled = false;
            }
            }

            // Get each component of the address from the place details
            // and fill the corresponding field on the form.
            for (var i = 0; i < place.address_components.length; i++) {
            var addressType = place.address_components[i].types[0];
            if (componentForm[addressType] && document.getElementById(addressType + unique)) {
            var val = place.address_components[i][componentForm[addressType]];
            document.getElementById(addressType + unique).value = val;
            }
            }
            }
            google.maps.event.addDomListener(window, "load", initAutocomplete);

            function geolocate() {
            if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
            var geolocation = {
            lat: position.coords.latitude,
            lng: position.coords.longitude
            };
            var circle = new google.maps.Circle({
            center: geolocation,
            radius: position.coords.accuracy
            });
            autocomplete.setBounds(circle.getBounds());
            });
            }
            }

            <script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
            <div id="locationField">
            <input id="autocomplete" placeholder="Start typing your address" onFocus="geolocate()" type="text" />
            </div>
            <div id="addressone">
            <input type="text" id="street_number" name="street_number" />
            <input type="text" id="route" name="street_name" />
            <input type="text" id="locality" name="town_city" />
            <input type="text" id="administrative_area_level_1" name="administrative_area_level_1" />
            <input type="text" id="postal_code" name="postcode" />
            <input type="text" id="country" name="country" />
            </div>
            <div id="locationField2">
            <input id="autocomplete2" placeholder="Start typing your address" onFocus="geolocate()" type="text" />
            </div>
            <div id="addresstwo">
            <input type="text" id="street_number2" name="street_number2" />
            <input type="text" id="route2" name="street_name2" />
            <input type="text" id="locality2" name="town_city2" />
            <input type="text" id="administrative_area_level_12" name="administrative_area_level_12" />
            <input type="text" id="postal_code2" name="postcode2" />
            <input type="text" id="country2" name="country2" />
            </div>






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 5 '15 at 16:42

























            answered Nov 5 '15 at 15:53









            geocodezipgeocodezip

            125k10142172




            125k10142172

























                1














                This works like a charm :)



                thanks jQuery.



                function initMultiComplete() {
                jQuery('.maps-complete').each(function(){

                var id = jQuery(this).prop('id');
                var $this = jQuery(this);
                var parent = jQuery(this).parent('div');

                var jautocomplete = new google.maps.places.Autocomplete(document.getElementById(id), {types: ['geocode']});

                jautocomplete.addListener('place_changed', function () {

                var place = jautocomplete.getPlace();
                var address = $this.val();
                var lat = place.geometry.location.lat();
                var lng = place.geometry.location.lng();

                jQuery( '.maps-autocomplete-lat', parent ).val(lat);
                jQuery( '.maps-autocomplete-lng', parent ).val(lng);

                });

                });
                }


                script calls initMultiComplete as callback, and is loaded w/ async defer:



                https://maps.googleapis.com/maps/api/js?key=YOUR_KEY&libraries=places&callback=initMultiComplete





                share|improve this answer






























                  1














                  This works like a charm :)



                  thanks jQuery.



                  function initMultiComplete() {
                  jQuery('.maps-complete').each(function(){

                  var id = jQuery(this).prop('id');
                  var $this = jQuery(this);
                  var parent = jQuery(this).parent('div');

                  var jautocomplete = new google.maps.places.Autocomplete(document.getElementById(id), {types: ['geocode']});

                  jautocomplete.addListener('place_changed', function () {

                  var place = jautocomplete.getPlace();
                  var address = $this.val();
                  var lat = place.geometry.location.lat();
                  var lng = place.geometry.location.lng();

                  jQuery( '.maps-autocomplete-lat', parent ).val(lat);
                  jQuery( '.maps-autocomplete-lng', parent ).val(lng);

                  });

                  });
                  }


                  script calls initMultiComplete as callback, and is loaded w/ async defer:



                  https://maps.googleapis.com/maps/api/js?key=YOUR_KEY&libraries=places&callback=initMultiComplete





                  share|improve this answer




























                    1












                    1








                    1







                    This works like a charm :)



                    thanks jQuery.



                    function initMultiComplete() {
                    jQuery('.maps-complete').each(function(){

                    var id = jQuery(this).prop('id');
                    var $this = jQuery(this);
                    var parent = jQuery(this).parent('div');

                    var jautocomplete = new google.maps.places.Autocomplete(document.getElementById(id), {types: ['geocode']});

                    jautocomplete.addListener('place_changed', function () {

                    var place = jautocomplete.getPlace();
                    var address = $this.val();
                    var lat = place.geometry.location.lat();
                    var lng = place.geometry.location.lng();

                    jQuery( '.maps-autocomplete-lat', parent ).val(lat);
                    jQuery( '.maps-autocomplete-lng', parent ).val(lng);

                    });

                    });
                    }


                    script calls initMultiComplete as callback, and is loaded w/ async defer:



                    https://maps.googleapis.com/maps/api/js?key=YOUR_KEY&libraries=places&callback=initMultiComplete





                    share|improve this answer















                    This works like a charm :)



                    thanks jQuery.



                    function initMultiComplete() {
                    jQuery('.maps-complete').each(function(){

                    var id = jQuery(this).prop('id');
                    var $this = jQuery(this);
                    var parent = jQuery(this).parent('div');

                    var jautocomplete = new google.maps.places.Autocomplete(document.getElementById(id), {types: ['geocode']});

                    jautocomplete.addListener('place_changed', function () {

                    var place = jautocomplete.getPlace();
                    var address = $this.val();
                    var lat = place.geometry.location.lat();
                    var lng = place.geometry.location.lng();

                    jQuery( '.maps-autocomplete-lat', parent ).val(lat);
                    jQuery( '.maps-autocomplete-lng', parent ).val(lng);

                    });

                    });
                    }


                    script calls initMultiComplete as callback, and is loaded w/ async defer:



                    https://maps.googleapis.com/maps/api/js?key=YOUR_KEY&libraries=places&callback=initMultiComplete






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Jan 24 '18 at 15:51

























                    answered Jan 23 '18 at 17:39









                    fraforfrafor

                    64111




                    64111























                        0














                        This is an old question but I thought I'd post my solution to this in case it's helpful to others in the future. My solution handles any number of maps api autocomplete fields on a page. You'd need tag all autocomplete fields with a class name, in my case I've used the class name "address".



                        Now grab the collection of fields:



                        var input = document.getElementsByClassName('address');

                        for (var x = 0; x < input.length; x++) {
                        addListener(input[x]);
                        }


                        which calls a function called "addListener"



                        function addListener(el) {
                        var autocomplete = new google.maps.places.Autocomplete(el);

                        google.maps.event.addListener(autocomplete, 'place_changed', function () {
                        // Do whatever you want in here e.g.
                        // var place = autocomplete.getPlace();
                        });
                        }


                        Because it's a collection, you should be able to add any number of autocomplete fields to a page. Though naturally, you should check for undefined on the collection just in case you happen to have no autocomplete fields on the page.






                        share|improve this answer




























                          0














                          This is an old question but I thought I'd post my solution to this in case it's helpful to others in the future. My solution handles any number of maps api autocomplete fields on a page. You'd need tag all autocomplete fields with a class name, in my case I've used the class name "address".



                          Now grab the collection of fields:



                          var input = document.getElementsByClassName('address');

                          for (var x = 0; x < input.length; x++) {
                          addListener(input[x]);
                          }


                          which calls a function called "addListener"



                          function addListener(el) {
                          var autocomplete = new google.maps.places.Autocomplete(el);

                          google.maps.event.addListener(autocomplete, 'place_changed', function () {
                          // Do whatever you want in here e.g.
                          // var place = autocomplete.getPlace();
                          });
                          }


                          Because it's a collection, you should be able to add any number of autocomplete fields to a page. Though naturally, you should check for undefined on the collection just in case you happen to have no autocomplete fields on the page.






                          share|improve this answer


























                            0












                            0








                            0







                            This is an old question but I thought I'd post my solution to this in case it's helpful to others in the future. My solution handles any number of maps api autocomplete fields on a page. You'd need tag all autocomplete fields with a class name, in my case I've used the class name "address".



                            Now grab the collection of fields:



                            var input = document.getElementsByClassName('address');

                            for (var x = 0; x < input.length; x++) {
                            addListener(input[x]);
                            }


                            which calls a function called "addListener"



                            function addListener(el) {
                            var autocomplete = new google.maps.places.Autocomplete(el);

                            google.maps.event.addListener(autocomplete, 'place_changed', function () {
                            // Do whatever you want in here e.g.
                            // var place = autocomplete.getPlace();
                            });
                            }


                            Because it's a collection, you should be able to add any number of autocomplete fields to a page. Though naturally, you should check for undefined on the collection just in case you happen to have no autocomplete fields on the page.






                            share|improve this answer













                            This is an old question but I thought I'd post my solution to this in case it's helpful to others in the future. My solution handles any number of maps api autocomplete fields on a page. You'd need tag all autocomplete fields with a class name, in my case I've used the class name "address".



                            Now grab the collection of fields:



                            var input = document.getElementsByClassName('address');

                            for (var x = 0; x < input.length; x++) {
                            addListener(input[x]);
                            }


                            which calls a function called "addListener"



                            function addListener(el) {
                            var autocomplete = new google.maps.places.Autocomplete(el);

                            google.maps.event.addListener(autocomplete, 'place_changed', function () {
                            // Do whatever you want in here e.g.
                            // var place = autocomplete.getPlace();
                            });
                            }


                            Because it's a collection, you should be able to add any number of autocomplete fields to a page. Though naturally, you should check for undefined on the collection just in case you happen to have no autocomplete fields on the page.







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Dec 13 '17 at 12:08









                            BruceBruce

                            212




                            212






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f33547312%2fgoogle-maps-api-autocomplete-2nd-address-fields-on-same-page%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Liquibase includeAll doesn't find base path

                                How to use setInterval in EJS file?

                                Petrus Granier-Deferre