Blog
April 13, 2016 Marie H.

Auto populate location data based on zip

Auto populate location data based on zip

Photo by <a href="https://unsplash.com/@jameswiseman?utm_source=cloudista&utm_medium=referral" target="_blank" rel="noopener">James Wiseman</a> on <a href="https://unsplash.com/?utm_source=cloudista&utm_medium=referral" target="_blank" rel="noopener">Unsplash</a>

Today I had to build a simple registration form, to make things a bit faster for the end user I went with the basic you provide me with your ZipCode and I’ll fill out the City and State that you see most places. In order to do this we use the Google Geocode API which makes this a actually fairly simple task to finish. Below is pieces of the implementation for your use.

Although this is using AngularJS it should be simple enough to abstract out to plain old javascript or your favorite framework.

HTML markup

      Zip Code



      City



      State



      Register

This will just build a very basic bootstrap form that shows just a zipcode.

JS Controller

app.controller("registerCtrl", function($scope, $http) {
  var vm = $scope;
  vm.user = {};

  /*
   * Get Zip Code From Google API
   */
  vm.getZipData = function(zipcode) {
    var isValidZip = /(^\d{5}$)|(^\d{5}-\d{4}$)/.test(zipcode);
    if ( isValidZip ) {
      vm.zipCodeValid = true;
      var url = 'http://maps.googleapis.com/maps/api/geocode/json?address=' + zipcode;
      $http.get(url).then(function(res) {
        vm.user.patientCity = res.data.results[0].address_components[1].long_name;
        vm.user.patientState = res.data.results[0].address_components[2].long_name;
        console.log(res);
      }, function(res) {
        console.log("Failed getting data from Google");
      });
    } else {
      vm.zipCodeValid = false;
    }
  }

  /*
   * Reset Register Form
   */
  vm.resetRegister = function() {
    vm.user = {};
  };

  /*
   * Register User
   */
  vm.registerUser = function(user) {
    console.log(user);
  };

  vm.$watch('user.zipCode', function() {
    vm.getZipData(vm.user.zipCode);
  });

});

Now once the above code is in place you will see the form auto populate when a valid zip code is added as input.