如何添加Google地图自动完成搜索框?

82

我正在尝试为网站添加谷歌自动完成搜索框,以便用户可以尽可能轻松地搜索地址。

我的问题是,我已经在这里查看了众多问题以及有关此事的Google Maps Javascript API v3和一些教程,但它们都将自动完成功能与嵌入式谷歌地图上的映射捆绑在一起。

目前我只需要自动完成输入框,而非可视化的位置映射。不幸的是,我无法确定API的哪些部分与此相关,并且我查看的每个示例都包括大量用于地图的JavaScript代码。

我该如何仅添加自动完成输入功能?


13个回答

132

这段代码中有很大一部分是可以省略的。

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

1
这真的帮助了我很多,因为我和发帖者遇到了同样的问题。谢谢! - scott.schaffer
5
只是为了补充这个答案,您可以通过在“script”查询中添加“callback”参数来避免“window,'load'”事件:https://maps.googleapis.com/maps/api/js?key=KEY&libraries=places&callback=initialize - Gus
如何将结果限制在特定的国家? - StealthTrails
7
请使用以下代码:<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"> - Edward
@user3411192 谢谢,我明白了。 - Ketav
显示剩余6条评论

26

如果你想获取纬度和经度,可以使用以下简单的代码:

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

谢谢,这个完美工作。问题是:如果有人在搜索框中输入一个位置并按下回车键,而没有点击建议列表,那么经纬度值不会更新。有没有解决办法? - RobbTe

11

现在使用Google Maps/Places API需要使用API密钥,因此API网址将从

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

9

只需复制并粘贴以下示例代码。

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

这个链接中可以找到格式良好的代码,与Google地图自动完成搜索框相关。 http://jon.kim/how-to-add-google-maps-autocomplete-search-box/

7

我一直在尝试这个,看起来你需要同时激活Google地点和JavaScript Maps 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>

2

使用Google Maps JavaScript API和places库在网页中实现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 JavaScript API的自动完成搜索框及地图和信息窗口


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

1
// 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());
    });
  }
}

1

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


1

请按照下面的代码进行操作。

将此代码添加到你的TS文件中。

在你的类顶部声明此代码。

declare var google;

声明Map和input的ViewChild。
@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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接