Google Map API限制在此代码中自动完成

时间:2016-03-24 06:20:10

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

我正在使用谷歌地图API,但我想将搜索限制在特定国家/地区

我可以使用此代码

componentRestrictions: countryRestrict

但是我把它放在哪里我的自动完成搜索框代码在

之下
var input = document.getElementById('pac-input');
        var searchBox = new google.maps.places.SearchBox(input);
        map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

下面的任何搜索框事件监听器
   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) {
            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);
        });/* Search box result */

我把代码放在哪里

componentRestrictions: countryRestrict

1 个答案:

答案 0 :(得分:0)

您必须在自定义的位置限制自动填充,因此:,

var options = {
types: ['(cities)'],
componentRestrictions: {country: 'de'}/
};

autocomplete = new google.maps.places.Autocomplete(input, options);