Javascript 绑定google在文本框上放置自动完成,而不实例化google地图

Javascript 绑定google在文本框上放置自动完成,而不实例化google地图,javascript,jquery,google-maps,google-places,Javascript,Jquery,Google Maps,Google Places,我正在尝试在我的网站上添加GooglePlacesAutoComplete。我在使用Autocomplete绑定我的搜索文本框时遇到了一个问题,而没有使用实例化谷歌地图。我想做的是,我想在我的搜索字段中使用自动完成作为文本建议。但遗憾的是,我看到的所有教程都与谷歌地图一起使用。这有什么办法吗 提前感谢。请参阅此Google Geo-Dev博客帖子: 它有到相关方法的链接,包括Autocomplete.getPlace() 它还指出,“您可以在任何应用程序中自由使用Autocomplete,即使您

我正在尝试在我的网站上添加GooglePlacesAutoComplete。我在使用Autocomplete绑定我的搜索文本框时遇到了一个问题,而没有使用实例化谷歌地图。我想做的是,我想在我的搜索字段中使用自动完成作为文本建议。但遗憾的是,我看到的所有教程都与谷歌地图一起使用。这有什么办法吗


提前感谢。

请参阅此Google Geo-Dev博客帖子:

它有到相关方法的链接,包括
Autocomplete.getPlace()


它还指出,“您可以在任何应用程序中自由使用Autocomplete,即使您没有显示地图。我们所要求的是,当您在没有地图的情况下使用Autocomplete时,您可以在文本字段下显示‘由谷歌提供动力’徽标。”

伙计们,您可以使用以下代码

 <!DOCTYPE html>
    <html>
      <head>
        <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&sensor=false&libraries=places"></script>
        <script>
            var autocomplete;
            function initialize() {
              autocomplete = new google.maps.places.Autocomplete(
                  /** @type {HTMLInputElement} */(document.getElementById('autocomplete')),
                  { types: ['geocode'] });
              google.maps.event.addListener(autocomplete, 'place_changed', function() {
              });
            }
        </script>
      </head>
      <body onload="initialize()">
        <div id="locationField">
          <input id="autocomplete" placeholder="Enter your address" onFocus="geolocate()" type="text"></input>
        </div>
      </body>
    </html>

var自动完成;
函数初始化(){
autocomplete=new google.maps.places.autocomplete(
/**@type{HTMLInputElement}*/(document.getElementById('autocomplete'),
{类型:['geocode']});
google.maps.event.addListener(自动完成,'place\u changed',函数(){
});
}
编辑:谷歌地图现在需要一个新版本才能运行。


function initialize()
    {
        var input = document.getElementById('location');
        var autocomplete = new google.maps.places.Autocomplete(
                /** @type {HTMLInputElement} */(input),
                {
                    types: ['(cities)'],
                });
        google.maps.event.addListener(autocomplete, 'place_changed', function() {
            var place = autocomplete.getPlace();
            if (!place.geometry) {
                return;
            }
            //document.getElementById('fLat').value = place.geometry.location.lat();
            //document.getElementById('fLong').value = place.geometry.location.lng();

            var 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(' ');
            }
            LoadEventCategory();
            LoadYelpData();
        });
    }

    google.maps.event.addDomListener(window, 'load', initialize);
到 函数validAddr(){ 如果(IsplaceChange==false) { 如果($(“#taddress”).val!=”){ $(“#taddress error”).html(“”); } $(“#taddress”).val(空) //$(“#时尚服饰错误”).html(“请输入有效位置”); } }; var自动完成; 函数初始化1(){ autocomplete=new google.maps.places.autocomplete( (document.getElementById('taddress')), {类型:['geocode']}); google.maps.event.addListener(自动完成,'place\u changed',函数(){ }); } var IsplaceChange=false; $(文档).ready(函数(){ var input=document.getElementById('TadAddress'); var autocomplete=new google.maps.places.autocomplete(输入,{types:['(cities)]}); google.maps.event.addListener(自动完成,'place\u changed',函数(){ var place=autocomplete.getPlace(); IsplaceChange=true; }); $(“#taddress”).keydown(函数(){ IsplaceChange=false; }); }); $(“#taddress”).keyup(函数(){ 变量a=$(“#taddress”).val(); 如果(a.match(/^[t`~!@@$%^&*()|+\-=?;:'“\{\}\[\]\\\/]+/gi)){ $(“#taddress error”).html(“不允许空白和特殊字符”); $(“#taddress”).val(空); //document.form1.text1.focus(); 返回false; } 否则{ $(“#taddress error”).html(“”); //document.form1.text1.focus(); 返回true; } }); 函数validateADR2(){ 如果($(“#taddress”).val()=“”) { $(“#taddress error”).html(“请输入有效位置”); 返回false; } 否则{ $(“#taddress错误”)。
                <div class="col-sm-4">
                                    <span class="input input--hoshi">
                                        <input class="input__field input__field--hoshi" id="taddress" type="text"  placeholder="" onmouseover="notnull2(this)" onblur="validtaddr(this); validateaddr2(this);" >
                                        <label class="input__label input__label--hoshi input__label--hoshi-color-2" for="dateto">
                                            <span class="input__label-content input__label-content--hoshi">To</span>
                                        </label>
                                    </span>
                                    <div id="taddress-error" style="color:red"></div>
                                    <script>

                                        function validtaddr() {
                                            if (IsplaceChange == false)
                                            {


                                                if ($("#taddress").val != "") {

                                                    $("#taddress-error").html(" ");
                                                }

                                                $("#taddress").val(null)
                                               //  $("#faddress-error").html("please Enter valid location");

                                            }

                                        };



                                    </script>
                                                                    <script>
                                        var autocomplete;
                                        function initialize1() {
                                          autocomplete = new google.maps.places.Autocomplete(
                                              (document.getElementById('taddress')),
                                              { types: ['geocode'] });
                                          google.maps.event.addListener(autocomplete, 'place_changed', function() {
                                          });
                                        }
                                                                    </script>
                                                                    <script>
                                                var IsplaceChange = false;
                                                $(document).ready(function () {
                                                    var input = document.getElementById('taddress');
                                                    var autocomplete = new google.maps.places.Autocomplete(input, { types: ['(cities)'] });

                                                    google.maps.event.addListener(autocomplete, 'place_changed', function () {
                                                        var place = autocomplete.getPlace();

                                                        IsplaceChange = true;
                                                    });

                                                    $("#taddress").keydown(function () {
                                                        IsplaceChange = false;
                                                    });


                                                });
                                    </script>
                                    <script>

                                        $("#taddress").keyup(function () {
                                            var a = $("#taddress").val();
                                        if (a.match(/^[ t`~!@@#$%^&*()_|+\-=?;:'"<>\{\}\[\]\\\/]+/gi)) {


                                            $("#taddress-error").html("White space & special char are not allow");
                                            $("#taddress").val(null);
                                            //document.form1.text1.focus();
                                            return false;
                                        }
                                        else {

                                            $("#taddress-error").html("");
                                            //document.form1.text1.focus();
                                            return true;
                                        }

                                    });
                                    </script>




                                    <script>

                                            function validateaddr2() {
                                                if ($("#taddress").val() == "")
                                                {
                                                    $("#taddress-error").html("Please enter valid location");
                                                    return false;
                                                }
                                                else {
                                                    $("#taddress-error").html("");
                                                }
                                            }
                                            function notnull2() {
                                                if ($("#taddress").val != "") {

                                                    $("#taddress-error").html(" ");
                                                }
                                                else {
                                                    $("#taddress-error").html(" Please enter valid location");
                                                }
                                            }
                                    </script>
                                </div>
<script type="text/javascript">
  function initAutocomplete() {
    // Create the autocomplete object, restricting the search to geographical
    // location types.
    autocomplete = new google.maps.places.Autocomplete(
        /** @type {!HTMLInputElement} */(document.getElementById('YOUR_INPUT_ELEMENT_ID')),
        {types: ['geocode']});

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

  function fillInAddress() {
    // Get the place details from the autocomplete object.
    var place = autocomplete.getPlace();

  }
    </script>
<input type="text" id="YOUR_INPUT_ELEMENT_ID" />
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initAutocomplete" async defer></script>
<head>
  <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?key=Secretkey&libraries=places" async defer></script>
  <script>
    var autocomplete;
    function initialize() {
      autocomplete = new google.maps.places.Autocomplete(
        /** @type {HTMLInputElement} */
        (document.getElementById('autocomplete')),
        { types: ['geocode'] }
      );
      google.maps.event.addListener(autocomplete, 'place_changed', function() {});
    }
  </script>
</head>

<div id="locationField">
  <input id="autocomplete" name="location" placeholder="Enter your address" onFocus="geolocate()" type="text"></input>
</div>
<script>
  google.maps.event.addDomListener(window, 'load', initialize);
    function initialize() {
      var input = document.getElementById('autocomplete_search');
      var autocomplete = new google.maps.places.Autocomplete(input);
      autocomplete.addListener('place_changed', function () {
      var place = autocomplete.getPlace();
      // place variable will have all the information you are looking for.
      $('#lat').val(place.geometry['location'].lat());
      $('#long').val(place.geometry['location'].lng());
    });
  }
</script>
<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Places Search Box</title>
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      #description {
        font-family: Roboto;
        font-size: 15px;
        font-weight: 300;
      }

      #infowindow-content .title {
        font-weight: bold;
      }

      #infowindow-content {
        display: none;
      }

      #map #infowindow-content {
        display: inline;
      }

      .pac-card {
        margin: 10px 10px 0 0;
        border-radius: 2px 0 0 2px;
        box-sizing: border-box;
        -moz-box-sizing: border-box;
        outline: none;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
        background-color: #fff;
        font-family: Roboto;
      }

      #pac-container {
        padding-bottom: 12px;
        margin-right: 12px;
      }

      .pac-controls {
        display: inline-block;
        padding: 5px 11px;
      }

      .pac-controls label {
        font-family: Roboto;
        font-size: 13px;
        font-weight: 300;
      }

      #pac-input {
        background-color: #fff;
        font-family: Roboto;
        font-size: 15px;
        font-weight: 300;
        margin-left: 12px;
        padding: 0 11px 0 13px;
        text-overflow: ellipsis;
        width: 400px;
      }

      #pac-input:focus {
        border-color: #4d90fe;
      }

      #title {
        color: #fff;
        background-color: #4d90fe;
        font-size: 25px;
        font-weight: 500;
        padding: 6px 12px;
      }
      #target {
        width: 345px;
      }
    </style>
  </head>
  <body>
    <input id="pac-input" class="controls" type="text" placeholder="Search Box">
    <div id="map" style="height: 200px;width: 200px"></div>
    <script>
      // This example adds a search box to a map, using the Google Place Autocomplete
      // feature. People can enter geographical searches. The search box will return a
      // pick list containing a mix of places and predicted search terms.

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

      function initAutocomplete() {
        var map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: -33.8688, lng: 151.2195},
          zoom: 13,
          mapTypeId: 'roadmap'
        });

        // Create the search box and link it to the UI element.
        var input = document.getElementById('pac-input');
        var searchBox = new google.maps.places.SearchBox(input);
        map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

        // Bias the SearchBox results towards current map's viewport.
        map.addListener('bounds_changed', function() {
          searchBox.setBounds(map.getBounds());
        });

        var markers = [];
        // Listen for the event fired when the user selects a prediction and retrieve
        // more details for that place.
        searchBox.addListener('places_changed', function() {
          var places = searchBox.getPlaces();

          if (places.length == 0) {
            return;
          }

          // Clear out the old markers.
          markers.forEach(function(marker) {
            marker.setMap(null);
          });
          markers = [];

          // For each place, get the icon, name and location.
          var bounds = new google.maps.LatLngBounds();
          places.forEach(function(place) {
            if (!place.geometry) {
              console.log("Returned place contains no geometry");
              return;
            }
            var icon = {
              url: place.icon,
              size: new google.maps.Size(71, 71),
              origin: new google.maps.Point(0, 0),
              anchor: new google.maps.Point(17, 34),
              scaledSize: new google.maps.Size(25, 25)
            };

            // Create a marker for each place.
            markers.push(new google.maps.Marker({
              map: map,
              icon: icon,
              title: place.name,
              position: place.geometry.location
            }));

            if (place.geometry.viewport) {
              // Only geocodes have viewport.
              bounds.union(place.geometry.viewport);
            } else {
              bounds.extend(place.geometry.location);
            }
          });
          map.fitBounds(bounds);
        });
      }

    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=your key&libraries=places&callback=initAutocomplete"
         async defer></script>
  </body>
</html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style type="text/css">
    body
    {
        font-family: Arial;
        font-size: 10pt;
    }
</style>
</head>
<body>
 <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=PLZ_ADD_YOUR_GOOGLE_API_KEY_HERE&sensor=false&libraries=places"></script>
<script type="text/javascript">
    google.maps.event.addDomListener(window, 'load', function () {
        var places = new google.maps.places.Autocomplete(document.getElementById('txtPlaces'));
        google.maps.event.addListener(places, 'place_changed', function () {
            var place = places.getPlace();
            var address = place.formatted_address;
            var latitude = place.geometry.location.lat();
            var longitude = place.geometry.location.lng();
            var mesg = "Address: " + address;
            mesg += "\nLatitude: " + latitude;
            mesg += "\nLongitude: " + longitude;
            alert(mesg);
        });
    });
</script>
<span>Location:</span>
<input type="text" id="txtPlaces" style="width: 250px" placeholder="Enter a location" />
</body>
</html>