Adding Multiple Instances of Google Places on Same Page

37,208

Solution 1

It is simply problem.
You using two IDs "autocomplete" and "autocomplete2"
but initialized only ID "autocomplete".
Try add this code to initialize().

Javascript

autocomplete2 = new google.maps.places.Autocomplete(document.getElementById('autocomplete2'), { types: [ 'geocode' ] });
google.maps.event.addListener(autocomplete2, 'place_changed', function() {
  fillInAddress();
});

Solution 2

A more dynamic approach. You don't need to initialise your element ids.

var inputs = document.getElementsByClassName('query');

var options = {
  types: ['(cities)'],
  componentRestrictions: {country: 'fr'}
};

var autocompletes = [];

for (var i = 0; i < inputs.length; i++) {
  var autocomplete = new google.maps.places.Autocomplete(inputs[i], options);
  autocomplete.inputId = inputs[i].id;
  autocomplete.addListener('place_changed', fillIn);
  autocompletes.push(autocomplete);
}

function fillIn() {
  console.log(this.inputId);
  var place = this.getPlace();
  console.log(place. address_components[0].long_name);
}
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places&key=AIzaSyC0Laj_Wk3kjFM-S8mYljc-WWCeesoDA_M"></script>

<input id="query-0" class="query" type="text"/>
<input id="query-1" class="query" type="text"/>
<input id="query-2" class="query" type="text"/>

Solution 3

Here is my solution, but needs jQuery

var autocomplete = {};
		var autocompletesWraps = ['test', 'test2'];

		var test_form = { street_number: 'short_name', route: 'long_name', locality: 'long_name', administrative_area_level_1: 'short_name', country: 'long_name', postal_code: 'short_name' };
		var test2_form = { street_number: 'short_name', route: 'long_name', locality: 'long_name', administrative_area_level_1: 'short_name', country: 'long_name', postal_code: 'short_name' };

		function initialize() {

			$.each(autocompletesWraps, function(index, name) {
			
				if($('#'+name).length == 0) {
					return;
				}

				autocomplete[name] = new google.maps.places.Autocomplete($('#'+name+' .autocomplete')[0], { types: ['geocode'] });
					
				google.maps.event.addListener(autocomplete[name], 'place_changed', function() {
					
					var place = autocomplete[name].getPlace();
					var form = eval(name+'_form');

					for (var component in form) {
						$('#'+name+' .'+component).val('');
						$('#'+name+' .'+component).attr('disabled', false);
					}
					
					for (var i = 0; i < place.address_components.length; i++) {
						var addressType = place.address_components[i].types[0];
						if (typeof form[addressType] !== 'undefined') {
						  var val = place.address_components[i][form[addressType]];
						  $('#'+name+' .'+addressType).val(val);
						}
					}
				});
			});
		}
html, body, #map-canvas {
        height: 100%;
        margin: 0px;
        padding: 0px
      }
	   #locationField, #controls {
        position: relative;
        width: 480px;
      }
      #autocomplete {
        position: absolute;
        top: 0px;
        left: 0px;
        width: 99%;
      }
      .label {
        text-align: right;
        font-weight: bold;
        width: 100px;
        color: #303030;
      }
      table {
        border: 1px solid #000090;
        background-color: #f0f0ff;
        width: 480px;
        padding-right: 2px;
      }
      table td {
        font-size: 10pt;
      }
      .field {
        width: 99%;
      }
      .slimField {
        width: 80px;
      }
      .wideField {
        width: 200px;
      }
      #locationField {
        height: 20px;
        margin-bottom: 2px;
      }
<!DOCTYPE html>
<html>
  <head>
    <title>Place Autocomplete Address Form</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
	<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <link type="text/css" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500">
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places"></script>
  </head>

  <body onload="initialize()">
  
  <div id="test">
    
    <input class="autocomplete" placeholder="Enter your address" type="text"></input>

    <table>
      <tr>
        <td class="label">Street address</td>
        <td class="slimField"><input class="field street_number" disabled="true"></input></td>
        <td class="wideField" colspan="2"><input class="field route" disabled="true"></input></td>
      </tr>
      <tr>
        <td class="label">City</td>
        <td class="wideField" colspan="3"><input class="field locality" disabled="true"></input></td>
      </tr>
      <tr>
        <td class="label">State</td>
        <td class="slimField"><input class="field administrative_area_level_1" disabled="true"></input></td>
        <td class="label">Zip code</td>
        <td class="wideField"><input class="field postal_code" disabled="true"></input></td>
      </tr>
      <tr>
        <td class="label">Country</td>
        <td class="wideField" colspan="3"><input class="field country" disabled="true"></input></td>
      </tr>
    </table>
</div>

<br /><br />
	
<div id="test2">	
	
    <input class="autocomplete" placeholder="Enter your address" type="text"></input>
    
	<table>
      <tr>
        <td class="label">Street address</td>
        <td class="slimField"><input class="field street_number" disabled="true"></input></td>
        <td class="wideField" colspan="2"><input class="field route" disabled="true"></input></td>
      </tr>
      <tr>
        <td class="label">City</td>
        <td class="wideField" colspan="3"><input class="field locality" disabled="true"></input></td>
      </tr>
      <tr>
        <td class="label">State</td>
        <td class="slimField"><input class="field administrative_area_level_1" disabled="true"></input></td>
        <td class="label">Zip code</td>
        <td class="wideField"><input class="field postal_code" disabled="true"></input></td>
      </tr>
      <tr>
        <td class="label">Country</td>
        <td class="wideField" colspan="3"><input class="field country" disabled="true"></input></td>
      </tr>
    </table>
</div>

</body>
</html>

Solution 4

I couldn't get Joseph's solution to work above, as the second input field would still fill in the first input field, so this is based on his answer with some amendments.

I have two address form on the same page, and they display dynamically depending on the customer's previous selection, so I started by creating a unique id, then add the usual fields.

<div id="<?php if( isset( $postcode_context ) && $postcode_context == "collection") { echo "collections-autocomplete-fields";} else {echo "autocomplete-fields";}?>" class="new-address-fields">
    <div class="fields">
    <div class="row form-group">
        <div class="col-xs-12 col-sm-6">
            <label for="Address1">Building Number/Name *</label>
            <input type="text" class="form-control field" name="Address1" id="street_number">
        </div>
        <div class="col-xs-12 col-sm-6">
            <label for="Address2">Address line 1 *</label>
            <input type="text" class="form-control field" name="Address2" id="route">
        </div>
    </div>
    <div class="row form-group">
        <div class="col-xs-12 col-sm-6">
            <label for="Address2">Address line 2</label>
            <input type="text" class="form-control field" name="Address2" id="route_two">
        </div>
        <div class="col-xs-12 col-sm-6">
            <label for="Town">Town *</label>
            <input type="text" class="form-control field" name="Town" id="locality">
        </div>
    </div>
    <div class="row form-group">
        <div class="col-xs-12 col-sm-6">
            <label for="County">County</label>
            <input type="text" class="form-control field" name="County" id="administrative_area_level_1">
        </div>
        <div class="col-xs-12 col-sm-6 wideField">
            <label for="Postcode">Postcode *</label>
            <input type="text" class="form-control field" name="Postcode" id="postal_code">
        </div>
    </div>
    <div class="row form-group">
        <div class="col-xs-12 col-sm-6 wideField">
            <label for="Country">Country *</label>
            <input type="text" class="form-control field" name="Postcode" id="country">
        </div>
    </div>
</div>

With jQuery as follows:

googlePlaces: function ($context) {
        var placeSearch, autocomplete;
        var componentForm = {
            street_number: 'short_name',
            route: 'long_name',
            locality: 'long_name',
            administrative_area_level_1: 'long_name',
            country: 'long_name',
            postal_code: 'short_name'
        };

        var componentForm2 = {
            street_number: 'short_name',
            route: 'long_name',
            locality: 'long_name',
            administrative_area_level_1: 'long_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'],
                    componentRestrictions: {
                        country: ['UK']
                    }
                });

            autocomplete2 = new google.maps.places.Autocomplete(
                /** @type {!HTMLInputElement} */
                (document.getElementById('collections-autocomplete')), {
                    types: ['geocode'],
                    componentRestrictions: {
                        country: ['UK']
                    }
                });

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

        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;
                }
            }
        }

        function fillInAddress2() {
            // Get the place details from the autocomplete object.
            var place = autocomplete2.getPlace();
            for (var component in componentForm2) {
                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 (componentForm2[addressType]) {
                    var val = place.address_components[i][componentForm2[addressType]];
                    $('#collections-autocomplete-fields #' + addressType).val(val);
                }
            }
        }

        // 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());
                });
            }
        }
        google.maps.event.addDomListener(window, 'load', initAutocomplete);
    }

First time answering a question in full on here, so hopefully I have met the criteria. Thanks to Joseph, who this answer is based on.

Solution 5

I have wrote a blog about this here -> https://lindarawson.com/adding-multiple-instances-of-google-places-on-same-page/

I took all of your answers, and made my own answer.

In the loading function of the page:


    $(document).ready(function() {
      var autocompletesWraps = ['facility_address', 'source_address'];
      createGeoListeners(autocompletesWraps);
    });

Then you have four functions:


    function createGeoListeners(autocompletesWraps) {
            var options = {types: ['geocode']};
            var inputs = $('.autocomplete');
            var autocompletes = [];
            for (var i = 0; i < inputs.length; i++) {
                var autocomplete = new google.maps.places.Autocomplete(inputs[i], options);
                autocomplete.inputId = inputs[i].id;
                autocomplete.parentDiv = autocompletesWraps[i];
                autocomplete.addListener('place_changed', fillInAddressFields);
                inputs[i].addEventListener("focus", function() {
                    geoLocate(autocomplete);
                }, false);
                autocompletes.push(autocomplete);
            }
        }
        function fillInAddressFields() {
            $('.googleerror').removeClass('is-valid is-invalid');
            var place = this.getPlace();
            for (var i = 0; i < place.address_components.length; i++) {
                var addressType = place.address_components[i].types[0];
                var val = place.address_components[i].long_name;
                //console.log("address Type " + addressType + " val " + val + " pd " + this.parentDiv);
                $('#'+this.parentDiv).find("."+addressType).val(val);
                $('#'+this.parentDiv).find("."+addressType).attr('disabled', false);
            }
        }
        function geoLocate(autocomplete) {
            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());
                });
            }
        }
        function gm_authFailure() { 
            $('.gm-err-autocomplete').addClass('is-invalid');
            swal("Error","There is a problem with the Google Maps or Places API","error");
        };

Hope this helps you.

Share:
37,208

Related videos on Youtube

Colin Keany
Author by

Colin Keany

Here to learn more about JS.

Updated on August 04, 2020

Comments

  • Colin Keany
    Colin Keany over 3 years

    I'm looking to include 2 instances of Google Places auto-complete on the same page. Looking to setup an input for a Pickup Location and an input for a Dropoff Location.

    I'm assuming it has to do with the ID of the input element, but even when I changed it to a class, it still wasn't working.

    This is what I currently have, and it works for the first field, but I can't figure out how to get a second input field to auto complete, or even show any signs of being anything other than a plain input text field.

    Any help is greatly appreciated!

    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true&libraries=places"></script>
    <script type="text/javascript">
      var placeSearch,autocomplete;
      function initialize() {
        autocomplete = new google.maps.places.Autocomplete(document.getElementById('autocomplete'), { types: [ 'geocode' ] });
        google.maps.event.addListener(autocomplete, 'place_changed', function() {
          fillInAddress();
        });
      }
      function fillInAddress() {
        var place = autocomplete.getPlace();
    
        for (var component in component_form) {
          document.getElementById(component).value = "";
          document.getElementById(component).disabled = false;
        }
    
        for (var j = 0; j < place.address_components.length; j++) {
          var att = place.address_components[j].types[0];
          if (component_form[att]) {
            var val = place.address_components[j][component_form[att]];
            document.getElementById(att).value = val;
          }
        }
      }
    </script>
    

    HTML

    <body onload="initialize()">
    <form action="" method="post" name="theform" id="theform">
        <label>Pickup Location</label>
        <input type="text" name="PickupLocation" onfocus="geolocate()" placeholder="Enter your pickup location" id="autocomplete" autocomplete="off" />
    
        <label>Dropoff Location</label>
        <input type="text" name="DropoffLocation" onfocus="geolocate()" placeholder="Enter your dropoff location" id="autocomplete2" autocomplete="off" />
    </form>
    </body>
    
  • Colin Keany
    Colin Keany over 10 years
    Ahh, such a stupid thing for me to have missed! This worked perfectly, thank you!
  • Cristiano Maia
    Cristiano Maia almost 7 years
    Almost worked for me but the result of the search from both fields are being displayed on form 1.
  • png
    png almost 6 years
    The instantiation is dynamic but it's not very flexible. fillIn() needs to work for all instances of your autocomplete. I rather be explicit in this case and instantiate a named var for additional autocompletes.
  • codeKonami
    codeKonami almost 6 years
    @NathanCH I don't really get your comment. Could you provide a jsfiddle to help me understand. I'd be really happy to edit my answer to add more flexibility.
  • Rob
    Rob about 5 years
    So much for not repeating yourself.
  • jamesthemullet
    jamesthemullet about 5 years
    Indeed, though I've since refactored since moving it to AngularJS.
  • Sam
    Sam over 4 years
    Hi, why do you need autocompletes = []. It seems not being used anywhere?
  • Amit Sharma
    Amit Sharma over 4 years
    How I can make this work on cloned elements. which loaded on click of cloned buttons