Jump to content

Auto complete city by xip code


MathiasReker
 Share

Recommended Posts

Hello,

 

I try to make the city autocomplete, when zip code is written!

 

Until now the code is working for one country, but I want the code to work in 9 countries.

 

This code works with danish. But if I choose an other country than Denmark, eg. Norway var country = 'DK'; should be var country = 'NO'; and so on. So before run this script, the selected country should be checked, so the script choose the right country.

 

Also if($(this).val().length == 4){ will change depending on how many caracters the zip code include. Maybe this should just be if($(this).val().length <= 6){ ?

 

Anyone who can tell me what I need to add the make this work? :-)

 

full code is below:

$(document).ready(function(){

//when the user clicks off of the zip field:
$('#postcode').keyup(function(){
  if($(this).val().length == 4){
  var postcode = $(this).val();
  var city = '';
  var state = '';
  var country = 'DK';
  //make a request to the google geocode api

  $.getJSON('http://maps.google.com/maps/api/geocode/json?components=country:'+country+'|postal_code:'+postcode+'&sensor=false')
  .success(function(response){
    //find the city and state
    var address_components = response.results[0].address_components;

    $.each(address_components, function(index, component){
      var types = component.types;
      $.each(types, function(index, type){

        if(type == 'locality') {
          city = component.long_name;
        }
        if(type == 'locality') {
          state = component.short_name;
        }
      });
    });
    //pre-fill the city and state
    var cities = response.results[0].postcode_localities;
    if(cities) {
      //turn city into a dropdown if necessary
      var $select = $(document.createElement('select'));
      console.log(cities);
      $.each(cities, function(index, locality){
        var $option = $(document.createElement('option'));
        $option.html(locality);
        $option.attr('value',locality);
        if(city == locality) {
          $option.attr('selected','selected');
        }
        $select.append($option);
      });
      $select.attr('id','city');
      $('#city_wrap').html($select);
    } else {
      $('#city').value(city);
    }
    $('#state').val(state);
  });
  }
});
});

Best regards

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...

Important Information

Cookies ensure the smooth running of our services. Using these, you accept the use of cookies. Learn More