Javascript 如何添加谷歌地图自动完成搜索框?

Javascript 如何添加谷歌地图自动完成搜索框?,javascript,google-maps-api-3,autocomplete,Javascript,Google Maps Api 3,Autocomplete,我试图在网站上添加一个谷歌自动完成搜索框,这样用户就可以尽可能轻松地搜索地址 我的问题是,我在这里查看了很多问题,以及谷歌地图Javascript API v3,关于这一点和一些教程,但它们都将自动完成功能与在嵌入式谷歌地图上映射功能捆绑在一起 我不需要直观地映射位置,我现在只需要autocomplete框,不幸的是我无法确定API的哪些部分与此相关,我所看到的每个示例都包含大量用于映射的JS 如何仅添加自动完成输入功能?此代码的很大一部分可以删除 HTML摘录: <head>

我试图在网站上添加一个谷歌自动完成搜索框,这样用户就可以尽可能轻松地搜索地址

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

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


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

此代码的很大一部分可以删除

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>

放置自动完成的地址表单
html,正文,#地图画布{
身高:100%;
边际:0px;
填充:0px
}
//此示例使用自动完成功能显示地址表单
//谷歌的PlacesAPI帮助用户填写信息。
var placeSearch,自动完成;
变量组件形式={
街道编号:“短名称”,
路线:'long_name',
地点:'long_name',
行政区域级别1:“短名称”,
国家:'long_name',
邮政编码:“短名称”
};
函数初始化(){
//创建自动完成对象,限制搜索
//地理位置类型。
autocomplete=new google.maps.places.autocomplete(
/**@type{HTMLInputElement}*/(document.getElementById('autocomplete'),
{类型:['geocode']});
//当用户从下拉列表中选择地址时,
//填充表单中的地址字段。
google.maps.event.addListener(自动完成,'place\u changed',函数(){
fillInAddress();
});
}
//[开始区域\填写表格]
函数fillInAddress(){
//从自动完成对象获取位置详细信息。
var place=autocomplete.getPlace();
for(componentForm中的var组件){
document.getElementById(组件).value='';
document.getElementById(组件).disabled=false;
}
//从place details中获取地址的每个组件
//并在表单上填写相应的字段。
对于(变量i=0;i
只需复制并粘贴下面的相同代码即可

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

位置
函数init(){
var input=document.getElementById('locationTextField');
var autocomplete=new google.maps.places.autocomplete(输入);
}
google.maps.event.addDomListener(窗口'load',init);
从这个链接可以找到格式良好的代码。

使用谷歌地图JavaScript API和places库在网页中实现谷歌地图自动完成搜索框

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>

函数initMap(){
var input=document.getElementById('searchInput');
var autocomplete=new google.maps.places.autocomplete(输入);
}

从这里可以找到完整的指南、源代码和实时演示-

要使用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>


我在这里使用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>

函数初始化(){
新的google.maps.places.Autocomplete(
(document.getElementById('autocomplete')){
类型:['geocode']
});
}
初始化();

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

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

函数初始化(){
var input=document.getElementById('searchTextField');
var autocomplete=new google.maps.places.autocomplete(输入);
google.maps.event.addListener(自动完成,'place\u changed',函数(){
var place=autocomplete.getPlace();
document.getElementById('city2')。value=place.name;
document.getElementById('cityla
<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>
<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 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);
}
<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>
<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>
declare var google;
@ViewChild('mapElement', {static: true}) mapNativeElement: ElementRef;
@ViewChild('autoCompleteInput', {static: true}) inputNativeElement: any;
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(): void {
    this.autoComplete();
  }
<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>
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);
}
<input id="searchTextField" type="text" size="50">
<input id="address" name="address" value='' type="hidden" placeholder="">
<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>