Friday 16 October 2015

Auto populate city and state using zip code(USA) in Laravel 5.1

Hi Everybody,

In this blog we will discuss how to auto populate USA city and state using zip code in Laravel 5.1.
For this we have to use google api for find city and state using zip code.

1. Routes


routes.php
Route::post('get/citystate', 'CityStateController@getCityState');

2. Controller

CityStateController.php

<?php

namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;

class AccountController extends Controller
{
 public function getCityState($blnUSA = true) {
        $data = Input::all();
        $zip = $data['zip'];
        $url = "http://maps.googleapis.com/maps/api/geocode/json?address=" . $zip . "&sensor=true";
        $address_info = file_get_contents($url);
        $json = json_decode($address_info);
        $city = "";
        $state = "";
        $country = "";
        $arrReturn = array();
        if (count($json->results) > 0) {
            //break up the components
            $arrComponents = $json->results[0]->address_components;

            foreach($arrComponents as $index=>$component) {
                $type = $component->types[0];

                if ($city == "" && ($type == "sublocality_level_1" || $type == "locality") ) {
                    $city = trim($component->long_name);
                }
                if ($state == "" && $type=="administrative_area_level_1") {
                    $state = trim($component->short_name);
                }
                if ($country == "" && $type=="country") {
                    $country = trim($component->short_name);

                    if ($blnUSA && $country!="US") {
                        $city = "";
                        $state = "";
                        break;
                    }
                }
                if ($city != "" && $state != "" && $country != "") {
                    //we're done
                    break;
                }
            }
        }
        return $arrReturn = array("city"=>$city, "state"=>$state, "country"=>$country);
    }

}

3. View

citystate.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://code.jquery.com/jquery.js"></script>
<script>

function is_int(value){
    if ((parseFloat(value) == parseInt(value)) && !isNaN(value)) {
        return true;
    } else {
        $("#city").val(''); /* Fill the data */
        $("#state").val('');
        return false;
    }
}

$("#zip").keyup(function() {
    $(".zip-error").hide(); /* In case they failed once before */
    var el = $(this);
    if ((el.val().length == 5) && (is_int(el.val()))) {
        $.ajax({
            url: '/get/citystate',
            type: "POST",
            data: "zip=" + el.val(),
            success: function(result, success) {
                $("#city").val(result['city']); /* Fill the data */
                $("#state").val(result['state']);
                if($("#city").val()=="" || $("#state").val()==""){
                    $(".zip-error").show(); /* Ruh row */
                }else{
                    $(".zip-error").hide(); /* In case they failed once before */
                }
            },
            error: function(result, success) {
                $(".zip-error").show(); /* Ruh row */
            }
        });
    }else{
        $(".zip-error").show(); /* Ruh row */
    }
});
</script>
</head>
<body>
<div class="container">
<div class="form-group">
<div class="row">
    <div class="col-md-4 mrgn_t_10">
        <input type="text" pattern="[0-9]*"  maxlength="5" class="form-control indent_zero" id="zip" placeholder="ZIP" name="zip" value=""><p class="zip-error" style="display: none">Not a real zip code.</p></div>

  <div class="col-md-4 mrgn_t_10">
  <input type="text" class="form-control indent_zero" id="city" placeholder="CITY" name="city" value=""></div>
  
  <div class="col-md-4 mrgn_t_10">
      <input type="text" class="form-control indent_zero" id="state" placeholder="STATE" name="state" value=""></div>
</div>
</div>
</div>
</body>
</html>

If you have any query you can post it in comment.
Thanks.

8 comments:

  1. You need to create a new routes that will render your view part and rest are in the blog :)

    ReplyDelete
  2. you need to create a new laravel 5.1 project, then create a new controller and create a new route to open a page containing view.

    ReplyDelete
  3. can you give me this problem solution:-.
    Create a cron script using job/events to update user location details like city, state, longitude, latitude etc. using the zipcode provided on the registration page. User google API service or any other to get the location information using zipcode.

    ReplyDelete
    Replies
    1. For api it is very easy, just create a GET api and call function getCityState() and input zip there.
      e.g your api is localhost:8000/address?zip=110099
      and route will be
      Route::get('address', 'CityStateController@getCityState')

      Delete