如何限制谷歌地图api autocomplete jQuery在一个国家

时间:2014-09-14 21:36:32

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

我尝试使用google map api将代码写入自动填充地址。

首先我初始化了地图标记和地理编码器。

var geocoder;
var map;
var marker;

function initialize(){
//MAP
  var latlng = new google.maps.LatLng(34.016827, -6.835604);
  var options = {
    zoom: 15,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  map = new google.maps.Map(document.getElementById("map_canvas"), options);

  //GEOCODER
  geocoder = new google.maps.Geocoder();

  marker = new google.maps.Marker({
    map: map,
    draggable: true
  });

}

然后jQuery自动完成我'

    $(document).ready(function() { 

  initialize();

  $(function() {
    $("#address").autocomplete({
      //This bit uses the geocoder to fetch address values
      source: function(request, response) {
        geocoder.geocode( {'address': request.term }, function(results, status) {
          response($.map(results, function(item) {
            return {
              label:  item.formatted_address,
              value: item.formatted_address,
              latitude: item.geometry.location.lat(),
              longitude: item.geometry.location.lng()
            }
          }));
        })
      },
      //This bit is executed upon selection of an address
      select: function(event, ui) {
        $("#latitude").val(ui.item.latitude);
        $("#longitude").val(ui.item.longitude);
        var location = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
        marker.setPosition(location);
        map.setCenter(location);
      }
    });
  });

现在我想限制一个国家/地区的自动填充功能,我做了一些搜索,但我找到了this

但是当我尝试在我的代码中做同样的事情时,我确实知道了。

我希望我会找到一些帮助和谢谢

2 个答案:

答案 0 :(得分:0)

我找到了如何限制研究只是我应该把这个地方与城市和国家联系起来

geocoderar.geocode( {'address': request.term + ' Rabat, MA' }

就我而言,拉巴特是这个城市,MA就是这个国家,每个国家都有一个代码link for country code

答案 1 :(得分:0)

您必须使用Component Filtering来完全限制搜索结果

因此,根据此,修改您的代码如下:

 $(document).ready(function() { 

  initialize();

  $(function() {
  $("#address").autocomplete({
  //This bit uses the geocoder to fetch address values
  source: function(request, response) {
    geocoder.geocode( 
    {
      'address': request.term, 
      'componentRestrictions':{'country':'IT'} //any country code...
    }, function(results, status) {
      response($.map(results, function(item) {
        return {
          label:  item.formatted_address,
          value: item.formatted_address,
          latitude: item.geometry.location.lat(),
          longitude: item.geometry.location.lng()
        }
      }));
    })
  },
  //This bit is executed upon selection of an address
  select: function(event, ui) {
    $("#latitude").val(ui.item.latitude);
    $("#longitude").val(ui.item.longitude);
    var location = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
    marker.setPosition(location);
    map.setCenter(location);
    }
  });
});
相关问题