JSFiddle - React, Tailwind, and code Playground

by denniswaltermartinez

HTML

<label for="txt-zip-code">Please enter your zipcode.</label>
<input type="text" id="txt-zip-code" maxlength="5" placeholder="48706" />
<div class="loading">Loading...</div>
<div id="details"></div>

CSS

.loading {
    display: none;
}

JavaScript

var nav = null;
getLocationByDevice();

/**
 *    No validation or error checking is here. 
 */
$('#txt-zip-code').keyup(function () {
    var _this = $(this),
        val = _this.val();

    if (val.length === 5) getLocationByZipcode(val);
});

function getLocationByDevice() {

    if (nav === null) nav = window.navigator;

    var geoloc = nav.geolocation;
    if (geoloc !== null) geoloc.getCurrentPosition(function(e) {
        console.log('success', e);
        // http://maps.googleapis.com/maps/api/geocode/json?latlng= 43.615581999999996,-84.24721199999999&sensor=false
    }, function(e) {
     console.log('error', e);   
    });
}

function getLocationByZipcode(zipcode) {
    var loading = $('.loading'),
        hidden = $('.hidden');

    loading.show();

    $.getJSON('http://maps.googleapis.com/maps/api/geocode/json', {
        address: zipcode,
        sensor: false
    }).done(function (e) {
        var location = {};

        console.log(e);

        // get the first result.
        var result = e.results[0],
            addressComponents = result.address_components,
            addressComponentsLength = addressComponents.length;

        if (typeof result === 'undefined' || typeof addressComponents === 'undefined') return;

        // no county was found.
        var template = ['<ul>'];
        for (var i in addressComponents)
        template.push('<li>' + addressComponents[i].long_name + '</li>');
        template.push('</ul>');

        loading.hide();
        $('#details').html(template.join(''));
    }).fail(function (e) {
        console.log('fail', e);
    });
}