【问题标题】:How to add Google Maps Autocomplete search box?如何添加谷歌地图自动完成搜索框?
【发布时间】:2012-11-21 07:11:43
【问题描述】:

我正在尝试将 Google 自动填充搜索框添加到网站,以便用户可以尽可能轻松地搜索地址。

我的问题是,我在这里查看了很多问题以及关于此的 Google Maps Javascript API v3 和一些教程,但它们都将自动完成功能捆绑在一起,并将其映射到嵌入式 Google 地图上。

我不需要直观地映射位置,我现在只需要自动完成框,不幸的是我无法确定 API 的哪些部分与此相关,并且我查看的每个示例都包含大量用于映射的 JS .

我怎样才能只添加自动完成输入功能?

【问题讨论】:

标签: javascript google-maps-api-3 autocomplete


【解决方案1】:

这段代码的很大一部分可以被删除。

HTML 摘录:

<head>
  ...
  <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
  ...
</head>
<body>
  ...
  <input id="searchTextField" type="text" size="50">
  ...
</body>

Javascript:

function initialize() {
  var input = document.getElementById('searchTextField');
  new google.maps.places.Autocomplete(input);
}

google.maps.event.addDomListener(window, 'load', initialize);

【讨论】:

  • 这对我解决与发帖者相同的问题帮助很大。谢谢!
  • 只是添加到这个答案中,您可以通过在 script 查询中添加 callback 参数来避免 window, 'load' 事件:https://maps.googleapis.com/maps/api/js?key=KEY&amp;libraries=places&amp;callback=initialize
  • 脚本标签中API KEY是在哪里添加的?
  • 如何获得KEY?
  • @jshaf 请改用此代码:&lt;script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&amp;libraries=places"&gt;
【解决方案2】:

要获取纬度和经度,您可以使用以下简单代码:

<html>
<head>
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script>
    <script>
        function initialize() {
          var input = document.getElementById('searchTextField');
          var autocomplete = new google.maps.places.Autocomplete(input);
            google.maps.event.addListener(autocomplete, 'place_changed', function () {
                var place = autocomplete.getPlace();
                document.getElementById('city2').value = place.name;
                document.getElementById('cityLat').value = place.geometry.location.lat();
                document.getElementById('cityLng').value = place.geometry.location.lng();
            });
        }
        google.maps.event.addDomListener(window, 'load', initialize);
    </script>
</head>
<body>
    <input id="searchTextField" type="text" size="50" placeholder="Enter a location" autocomplete="on" runat="server" />  
    <input type="hidden" id="city2" name="city2" />
    <input type="hidden" id="cityLat" name="cityLat" />
    <input type="hidden" id="cityLng" name="cityLng" />
</body>
</html>

【讨论】:

  • 感谢它完美无缺。题;如果有人在搜索框中输入了一个位置,然后单击输入,因此没有单击建议列表,则不会更新 lat 和 long 值。有解决办法吗?
【解决方案3】:

现在要使用 Google Maps/Places API,您需要使用 API 密钥。所以 API URL 将从

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script>

【讨论】:

    【解决方案4】:

    只需复制并粘贴下面的相同代码即可。

    <!DOCTYPE html>
    <html>
        <head>
            <script src="https://maps.googleapis.com/maps/api/jsvv=3.exp&sensor=false&libraries=places"></script>
        </head>
        <body>
            <label for="locationTextField">Location</label>
            <input id="locationTextField" type="text" size="50">
    
            <script>
                function init() {
                    var input = document.getElementById('locationTextField');
                    var autocomplete = new google.maps.places.Autocomplete(input);
                }
    
                google.maps.event.addDomListener(window, 'load', init);
            </script>
        </body>
    </html>
    

    可以从此链接找到格式良好的代码。 http://jon.kim/how-to-add-google-maps-autocomplete-search-box/

    【讨论】:

      【解决方案5】:

      使用带有地点库的 Google Maps JavaScript API 在网页中实现 Google Maps 自动完成搜索框。

      HTML

      <input id="searchInput" class="controls" type="text" placeholder="Enter a location">
      

      JavaScript

      <script>
      function initMap() {
          var input = document.getElementById('searchInput');
          var autocomplete = new google.maps.places.Autocomplete(input);
      }
      </script>
      

      完整的指南、源代码和现场演示可以从这里找到 - Google Maps Autocomplete Search Box with Map and Info Window

      【讨论】:

        【解决方案6】:

        所以我一直在玩这个,看来你需要激活地方和 js 地图 api。然后使用以下内容:

        HTML:

        <input id="searchTextField" type="text" size="50">
        <input id="address" name="address" value='' type="hidden" placeholder="">
        

        JS:

        <script>
        function initMap() {
          var input = document.getElementById('searchTextField');
          var autocomplete = new google.maps.places.Autocomplete(input);
          autocomplete.addListener('place_changed', function() {
            var place = autocomplete.getPlace();
            document.getElementById("address").value = JSON.stringify(place.address_components);
          });
        }
        </script>
        
        <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap" async defer></script>
        

        【讨论】:

          【解决方案7】:
          // 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(poenter code heresition) {
                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());
              });
            }
          }
          

          【讨论】:

            【解决方案8】:
            <input id="autocomplete" placeholder="Enter your address" type="text"/>
            <script src="~/Scripts/jquery-1.10.2.min.js"></script>
            <script type="text/javascript" src="https://mapenter code heres.googleapis.com/maps/api/js?key=AIzaSyC7vPqKI7qjaHCE1SPg6i_d1HWFv1BtODo&libraries=places"></script>
            <script type="text/javascript">
                function initialize() {
            
                    new google.maps.places.Autocomplete(
                    (document.getElementById('autocomplete')), {
                        types: ['geocode']
                    });
                }
            
                initialize();
            
            </script>
            

            【讨论】:

              【解决方案9】:

              按照下面的代码。

              将此添加到您的 TS 文件中

              宣布这一点,你班上的佼佼者。

              declare var google;
              

              为 Map 和输入声明子视图。

              @ViewChild('mapElement', {static: true}) mapNativeElement: ElementRef;
              @ViewChild('autoCompleteInput', {static: true}) inputNativeElement: any;
              

              此方法在 ngOnInit() 事件或 ngAfterViewInit() 事件上运行。

              autoComplete() {
                  const map = new google.maps.Map(this.mapNativeElement.nativeElement, {
                    center: {lat: -33.8688, lng: 151.2093},
                    zoom: 7
                  });
              
                  const infowindow = new google.maps.InfoWindow();
                  const infowindowContent = document.getElementById('infowindow-content');
              
                  infowindow.setContent(infowindowContent);
              
                  const marker = new google.maps.Marker({
                    map: map,
                    anchorPoint: new google.maps.Point(0, -29)
                  });
                  const autocomplete = new google.maps.places.Autocomplete(this.inputNativeElement.nativeElement as HTMLInputElement);
                  autocomplete.addListener('place_changed', () => {
                    infowindow.close();
                    marker.setVisible(false);
                    const place = autocomplete.getPlace();
              
                    let cus_location = {
                      lat: place.geometry.location.lat(),
                      long: place.geometry.location.lng()
                    }
              
                    console.log('place data :................', cus_location); 
                    localStorage.setItem('LOC_DATA', this.helper.encryptData(cus_location));
              
                    if (!place.geometry) {
                      // User entered the name of a Place that was not suggested and
                      // pressed the Enter key, or the Place Details request failed.
                      window.alert('No details available for input: ' + place.name );
                      return;
                    }
              
                    if (place.geometry.viewport) {
                      map.fitBounds(place.geometry.viewport);
                    } else {
                      map.setCenter(place.geometry.location);
                      map.setZoom(17);  // Why 17? Because it looks good.
                    }
              
                    marker.setPosition(place.geometry.location);
                    marker.setVisible(true);
                    let address = '';
                    if (place.address_components) {
                      address = [
                        (place.address_components[0] && place.address_components[0].short_name || ''),
                        (place.address_components[1] && place.address_components[1].short_name || ''),
                        (place.address_components[2] && place.address_components[2].short_name || '')
                      ].join(' ');
                    }
              
                    if(infowindowContent){
                      infowindowContent.children['place-icon'].src = place.icon;
                      infowindowContent.children['place-name'].textContent = place.name;
                      infowindowContent.children['place-address'].textContent = address;
                    } 
              
                    infowindow.open(map, marker);
                  });
              
                }
              

              在 ngAfterViewInit 上调用方法。

              ngAfterViewInit(): void {
                  this.autoComplete();
                }
              

              这就是 HTML 代码。请根据您的需要进行修改。

              <ion-content fullscreen>
                  <div class="location-col">
              
              
                      <div class="google-map">
                          <!-- <img src="../../assets/images/google-map.jpg" alt=""> -->
                          <div #mapElement id="map"></div>
                      </div>
              
              
                      <div class="location-info">
                          <h2>Where is your car located?</h2>
                          <p>Enter address manually or click location detector icon to use current address.</p>
                          <div class="form-group">
              
                              <div class="location-row">
                                  <input type="text" #autoCompleteInput class="location-input" [(ngModel)]="search_location" placeholder="Search location">
                                  <span class="location-icon" (click)="getCurrentLocation()">
                                      <img src="../../assets/images/location-icon.svg" alt="">
                                  </span>
                              </div>
              
                              <button type="button" class="location-search-btn" (click)="goToVendorSearch()">
                                  <i class="fa fa-angle-right"></i>
                              </button>
              
                          </div>
                      </div>
                  </div>
              </ion-content>
              

              【讨论】:

                【解决方案10】:

                我目前正在使用 Google API 来检索用户在表单/输入中输入的位置。我还使用了一个角度函数来显示当前位置并建议一个城市名称密码等...... - 添加谷歌 API index.html。
                &lt;script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=xxxxxxxx&amp;libraries=geometry,places"&gt;&lt;/script&gt;
                - 在输入框中添加 id 以获取字符串和字符。
                &lt;input id="autocomplete" type="text"(keydown)="checkAddress($event.target.value)"&gt;
                - 并在您的 component.ts 文件上创建函数。
                导入这些文件

                import * as _ from 'lodash';
                declare var google: any;
                
                 checkAddress(value) {
                    if (!value) {
                      this.model.location = _.cloneDeep(value);
                      this.rfpForm.controls['location'].setValue(this.model.location);
                    }
                  }
                
                initLocationAutocomplete() {
                    let autocomplete, place;
                    const getLocation = () => {
                        place = autocomplete.getPlace();
                        if (place && (place.formatted_address || place.name)) {  
                            // if you want set value in your form controls like this
                            this.model.location = _.cloneDeep(place.formatted_address || place.name);
                            // YourFormName.controls['location'].setValue(this.model.location);
                            // YourFormName.controls['location']['_touched'] = true;
                        }
                    };
                    autocomplete = new google.maps.places.Autocomplete((document.getElementById('autocomplete')), { types: ['geocode'] });
                    autocomplete.addListener('place_changed', getLocation);
                }
                

                【讨论】:

                  【解决方案11】:

                  <input type="text"required id="autocomplete">
                  
                  <script>
                  function initAutocomplete() {
                     new google.maps.places.Autocomplete(
                            (document.getElementById('autocomplete')),
                            {types: ['geocode']}
                     );
                  }
                  </script>
                  <script src="https://maps.googleapis.com/maps/api/js?key=&libraries=places&callback=initAutocomplete"
                                  async defer></script>

                  【讨论】:

                    【解决方案12】:
                    <!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">
                        <style>
                          html, body, #map-canvas {
                            height: 100%;
                            margin: 0px;
                            padding: 0px
                          }
                        </style>
                        <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&signed_in=true&libraries=places"></script>
                        <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 initialize() {
                      // 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.
                      google.maps.event.addListener(autocomplete, 'place_changed', function() {
                        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 = new google.maps.LatLng(
                              position.coords.latitude, position.coords.longitude);
                          var circle = new google.maps.Circle({
                            center: geolocation,
                            radius: position.coords.accuracy
                          });
                          autocomplete.setBounds(circle.getBounds());
                        });
                      }
                    }
                    // [END region_geolocation]
                    
                        </script>
                    
                        <style>
                          #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;
                          }
                          #address {
                            border: 1px solid #000090;
                            background-color: #f0f0ff;
                            width: 480px;
                            padding-right: 2px;
                          }
                          #address td {
                            font-size: 10pt;
                          }
                          .field {
                            width: 99%;
                          }
                          .slimField {
                            width: 80px;
                          }
                          .wideField {
                            width: 200px;
                          }
                          #locationField {
                            height: 20px;
                            margin-bottom: 2px;
                          }
                        </style>
                      </head>
                    
                      <body onload="initialize()">
                        <div id="locationField">
                          <input id="autocomplete" placeholder="Enter your address"
                                 onFocus="geolocate()" type="text"></input>
                        </div>
                    
                    
                      </body>
                    </html>
                    

                    【讨论】:

                    • 为什么不直接把api文档的链接发过来,而不是不参考就直接复制呢?
                    【解决方案13】:

                    我在这里使用 jQuery 来获取输入的文本并将所有代码包装在 $(document).ready() 中。确保您已为 Google Places API Web 服务准备好 API 密钥。在下面的脚本文件中替换它。

                    <input type="text" id="location">
                    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=[YOUR_KEY_HERE]&libraries=places"></script>
                    <script src="javascripts/scripts.js"></scripts>
                    

                    使用脚本文件加载自动完成类。您的 scripts.js 文件将如下所示。

                        // scripts.js custom js file
                    $(document).ready(function () {
                       google.maps.event.addDomListener(window, 'load', initialize);
                    });
                    
                    function initialize() {
                        var input = document.getElementById('location');
                        var autocomplete = new google.maps.places.Autocomplete(input);
                    }
                    

                    【讨论】:

                      猜你喜欢
                      • 2018-07-04
                      • 1970-01-01
                      • 2020-12-12
                      • 2018-09-17
                      • 2011-09-19
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      相关资源
                      最近更新 更多