【问题标题】:Adding Multiple Instances of Google Places on Same Page在同一页面上添加多个 Google Places 实例
【发布时间】:2013-12-23 08:11:44
【问题描述】:

我希望在同一页面上包含 2 个 Google 地方信息自动完成实例。希望为上车地点设置输入和为下车地点设置输入。

我假设它与输入元素的 ID 有关,但即使我将其更改为类,它仍然无法正常工作。

这是我目前拥有的,它适用于第一个字段,但我无法弄清楚如何让第二个输入字段自动完成,甚至不显示任何迹象,而不是纯输入文本字段。

非常感谢任何帮助!

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

【问题讨论】:

    标签: javascript google-places-api google-places


    【解决方案1】:

    更动态的方法。您不需要初始化元素 ID。

    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"/>

    【讨论】:

    • 实例化是动态的,但不是很灵活。 fillIn() 需要适用于自动完成的所有实例。在这种情况下,我宁愿明确并实例化一个命名的 var 以实现额外的自动完成。
    • @NathanCH 我真的不明白你的意见。你能提供一个jsfiddle来帮助我理解吗?我很乐意编辑我的答案以增加灵活性。
    【解决方案2】:

    这只是个问题。
    您使用两个 ID“autocomplete”和“autocomplete2”
    但仅初始化 ID“自动完成”。
    尝试将此代码添加到 initialize()。

    Javascript

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

    【讨论】:

    • 啊,我错过了这么愚蠢的事情!效果很好,谢谢!
    【解决方案3】:

    这是我的解决方案,但需要 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>

    【讨论】:

    • 如何在克隆元素上进行这项工作。在单击克隆按钮时加载
    【解决方案4】:

    我无法让 Joseph 的解决方案在上面工作,因为第二个输入字段仍会填写第一个输入字段,所以这是基于他的回答并进行了一些修改。

    我在同一页面上有两个地址表单,它们会根据客户之前的选择动态显示,所以我首先创建一个唯一的 id,然后添加常用字段。

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

    用jQuery如下:

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

    第一次在这里完整回答一个问题,所以希望我已经达到了标准。感谢 Joseph,此答案所依据的是谁。

    【讨论】:

    • 不要重复自己。
    • 确实如此,不过自从将其移至 AngularJS 后,我已经对其进行了重构。
    【解决方案5】:

    我在这里写了一篇关于这个的博客 -> https://lindarawson.com/adding-multiple-instances-of-google-places-on-same-page/

    我接受了你所有的答案,并做出了我自己的答案。

    在页面的加载功能中:

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

    那么你有四个函数:

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

    希望对你有所帮助。

    【讨论】:

    • 嗨,你为什么需要autocompletes = []。它似乎没有在任何地方使用?
    【解决方案6】:

    此解决方案有效,但有一个问题:

    var theFields = ['field1','field2','field3','field4'];
    function initialize() {
    // Create the autocomplete object, restricting the search
    // to geographical location types.
     for (i=0;i<cityFields.length; i++){
    
          autocomplete = new google.maps.places.Autocomplete((document.getElementById(cityFields[i])),
      { types: ['geocode'] })
      }
    
    // When the user selects an address from the dropdown,
    // populate the address fields in the form.
    google.maps.event.addListener(autocomplete, 'place_changed', function() {
    fillInAddress();
    });
    }
    

    不过,唯一的问题是如果页面上不存在 field1,则 field2 不会加载脚本。例如,在我的情况下,前 2 个字段存在于一个页面上,另外 2 个字段存在于另一个页面上,但脚本被添加到标题(wordpress 标题)...

    【讨论】:

      【解决方案7】:

      > 此代码对我有用。试着告诉我。

          // This example displays an address form, using the autocomplete feature
      // of the Google Places API to help users fill in the information.
      
      // This example requires the Places library. Include the libraries=places
      // parameter when you first load the API. For example:
      // <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
      
      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('autolocation')),
            {types: ['geocode']});
      
       autocomplete2 = new google.maps.places.Autocomplete(
            /** @type {!HTMLInputElement} */(document.getElementById('autolocation2')),
            {types: ['geocode']});      
      
        // 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', fillInAddress);   
      }
      
      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 (componentForm[addressType]) {
            var val = place.address_components[i][componentForm[addressType]];
            document.getElementById(addressType).value = 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());
          });
        }
      }
      

      【讨论】:

      • 几乎对我有用,但两个字段的搜索结果都显示在表单 1 上。
      【解决方案8】:
      <script type="text/javascript" >
      function initAutocomplete() {
      var input = document.getElementById('source');
      var searchBox = new google.maps.places.SearchBox(input);
                                  document.write(searchBox)
      
      
      var input = document.getElementById('destination');
      var searchBox1 = new google.maps.places.SearchBox(input);
                                  document.write(searchBox1)
      }
      </script>
      <script src="https://maps.googleapis.com/maps/api/js?  
      key=your_palce_api_key&libraries=places&callback=initAutocomplete"async defer></script>
      

      【讨论】:

        【解决方案9】:

        我在一个页面上遇到了多个自动完成的问题, 一个组件创建了自动完成功能,我不得不调用它两次

        问题是:自动完成功能仅适用于第一个输入,而不适用于第二个输入

        为我解决的问题是:将“uniqueId”作为道具传递给组件,并在组件中的“place_changed”事件侦听器中:

            const input = document.getElementById(uId);
            let autocomplete = new window.google.maps.places.Autocomplete(input);
            autocomplete.setComponentRestrictions({ "country": "il" });
            autocomplete.addListener("place_changed", () => { handlePlaceChange(autocomplete) })
        

        我现在很忙,如果有人需要更多信息,请联系我 shankehat@gmail.com

        【讨论】:

          【解决方案10】:
              function initialize() {
          
                autocomplete = new google.maps.places.Autocomplete(
                    (document.getElementById('autocomplete')),
          
                    { types: ['geocode'], componentRestrictions:countryRestrict });
          
          
                google.maps.event.addListener(autocomplete, 'place_changed', function() {
          
                  fillInAddress();
          
                });
          
                autocomplete2 = new 
          
              google.maps.places.Autocomplete(document.getElementById('autocomplete2'), { 
              types: [ 'geocode' ] });
          
                google.maps.event.addListener(autocomplete2, 'place_changed', function() {
          
                  fillInAddress();
          
                });
          
          
          }
          

          【讨论】:

            猜你喜欢
            • 2012-08-20
            • 2022-06-10
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多