如何添加Google地图自动填充搜索框?

时间:2012-12-03 18:48:46

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

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

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

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

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

13 个答案:

答案 0 :(得分:94)

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

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

您可以在http://www.redwoodtransit.org找到示例。

答案 1 :(得分:6)

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

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

答案 2 :(得分:6)

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

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

答案 3 :(得分:5)

要立即使用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 :(得分:2)

将Google Maps JavaScript API与地点库结合使用,以在网页中实施Google地图自动填充搜索框。

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

答案 5 :(得分: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());
    });
  }
}

答案 6 :(得分: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>

答案 7 :(得分:0)

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

答案 8 :(得分:0)

我在这里使用jQuery来获取输入的文本并将所有代码包装在$(document).ready()中。确保您已为Google Places API网络服务准备好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);
}

答案 9 :(得分:0)

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

答案 10 :(得分:0)

遵循以下代码。

将此添加到您的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>

答案 11 :(得分:0)

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

import * as _ from 'lodash';
declare var google: any;
initLocationAutocomplete() {
let autocomplete, place, model;
const getLocation = () => {
place = autocomplete.getPlace();
if (place && (place.formatted_address || place.name)) {  
// if you want set value in your form controls like 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);
}

答案 12 :(得分:0)

所以我一直在玩这个游戏,看来您需要同时激活地点和js maps api。然后使用以下命令:

HTML:

HEREDOC

JS:

add_shortcode('recentvideos' , 'printrecenttv');

function printrecenttv(){
    $recent_posts = wp_get_recent_posts(array(
        'numberposts' => 4, // Number of recent posts thumbnails to display
        'post_status' => 'publish', // Show only the published posts
        'post_type'  => "tv" //Show only Videos
    ));
    foreach($recent_posts as $post) : 
        $perm = get_permalink($post['ID']);
        $imgurl = get_the_post_thumbnail_url($post['ID'], 'full');
return <<<HTML
     <div class="videoposter">
        <a class="posterlink" href="$perm">
                <img class="posterimg" src="$imgurl">
            </a>
    </div>
HTML;
     endforeach; wp_reset_query();
}