Badr4si Badr4si - 5 months ago 59
jQuery Question

How to limit google map api autocomplete jQuery in a country

I tried to write code to autocomplete addresses with google map api.

First I initialized the map marker and geocoder.

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

}


Then a jQuery autocomplete I'

$(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);
}
});
});


Now I'd like to limit the autocomplete in one country, I did some search but I found this

But when I tried to do the same in my code I did know.

I hope I'll find some help and thanks

Answer

You have to use Component Filtering to fully restrict search results

So, according to this, modify your code as follows:

 $(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);
    }
  });
});
Comments