skip to Main Content

JAVASCRIPT Get Location From Zip Code Using Ziptastic

JAVASCRIPT get location from Zip code using Ziptastic


I am working on shopping cart project on Laravel. The client wants to pre-populate the location detail like City, Country, State etc…

So let’s see How I can pre-populate and fetch location form Zipcode. We are using the┬áZiptastic API for fetching the location form zipcode.

Let’s see how we can fetch the location, first of all, we are creating the HTML like

<div>
      <input type="text" name="zipcode" id="zipcode">
      <input type="button" name="submit" value="Get Location" id="getLocation">
      <div>
        <strong>Country : </strong><span id="country"></span><br/>
        <strong>County : </strong><span id="county"></span><br/>
        <strong>State : </strong><span id="state"></span><br/>
        <strong>City : </strong><span id="city"></span><br/>
      </div>
  </div>

Now, let’s create the JAVASCRIPT code for fetching the record from the Zipcode like

<script type="text/javascript">
    (function($){
      $(document).ready(function(){
        $("#getLocation").click(function(){
              var zipcode = $("#zipcode").val();
              if( zipcode == "" ){
                alert("Please Enter Zipcode");
              }
              jQuery.ajax({
                url: "https://zip.getziptastic.com/v2/US/" + zipcode,
                cache: false,
                dataType: "json",
                type: "GET",
                success: function(result, success) {
                  console.log(result);
                  $("#country").html(result.country);
                  $("#county").html(result.county);
                  $("#state").html(result.state);
                  $("#city").html(result.city);
                },
                error: function(result, success) {

                  jQuery(".zip-error").slideDown(300);

                }

              });
        });
      });
    })(jQuery)
  </script>

Now, you need to change the Country code from the API URL currently I set it to “US” for the testing purpose.

If you enter the US Zipcode 20036 then the output get something like

Country : US
County : District of Columbia
State : District of Columbia
City : Washington

The Ziptastic is the paid API you can find the more detail about Ziptastic from here.

 

Saroj

I am a web designer and developer part-time blogger. Write something on some free time. Find my every day thought here :)

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top