Author Archive

Full Stack Analogy for Dummies

I was discussing web programming with a bunch of urban planners only to find blank stares. To laypersons, the web is like a magical television feed that pipes into their computer screens from far away.  In reality, a web is a simple set of instructions telling your computer to create something fun and interesting.  In explaining the process of how entire technology departments create effective and maintainable websites, I had to describe the “stack” which like a layered cake allowed multiple people to seamlessly develop a website.  I stumbled in connecting each role to more relatable jobs, until recently I realized a fun analogy could be a restaurant.

The Ingredients – Code

All life began with the computer and a plethora of languages available to create the web with.  HTML is just the seasoning and plate presentation of a server-side steak dinner, which could be built of Python and php.  Sometimes these languages come pre-packaged into libraries, like pre-made sauces that help speed up the process.   Or if it’s good and you can’t tell the difference, we’ll serve you a WordPress frozen soup we’ve heated up (a content management system with our own spices). 

The Back Kitchen – Dev-Ops

Those who play with Linux servers sit in the dark back room making sure we can keep up with the booming web traffic of our hardcore ninja app.  Servers are the stoves that keep things cooking and feeding the masses.  Someone in the back has to know how to fix the deployment blender.  Purging logs like washing dishes.

The Cooks – Back-End Programmers

These people are wizards with server-side code.  They know exactly how long to prep and cook the steak.  They’ll slice zucchini the way you need it.  Server-side languages manipulate and produce the expected data, like measuring the ingredients exactly for a perfect souffle.  They execute recipes with precision so they’re not always concerned with how pretty things look once on the plate.

The Sous Chef – Front-End Programmers

In past days there were webmasters who tinkered with plain text.  Today front-end web languages like HTML, CSS, and JavaScript support the ability to have fully interactive and visually pleasurable websites.  They turn that raw server information into beautiful plate presentations that excite and challenge the eye and palate.  The back-end hands over the useful data, the grilled steak, and the front-end positions the steak on the plate, assembles the side dishes, and puts finishing touches.

The Head Chef – User Experience Designers

The head chef creates the plates and recipes everyone is busily cooking and perfecting. They set the look, the standard, the expectation.  A web designer today is designing user experience and providing visual guides to websites in addition to pixel perfect templates. Granted, a designer doesn’t necessarily drive the show come table service, they certainly set the way things will be done when they’re not there.

The House Manager and Host – CTO & Support

The chef doesn’t call all the shots, the ultimate decisions end up with the restaurant owner.  A development team is guided by a Chief Technology Officer who permeates all processes and layers.  Along with support people, they also solve client-facing problems and emergencies — the confused or disgruntled patrons.  Their steak is undercooked, there’s a hair in the soup, the waiter is rude, the web can “break” at many points in the process and so they come in to address these administrative issues.

The Wait Staff – Sales and Marketing

The business development and “growth” people will jab me in the side for calling them the wait staff.  In reality their role is very similar, they are selling the product and standing by it.  They’re delivering a promise to patrons that the menu is going to give them that great experience, for a price.  And any good salesperson will keep the client or diner happy.   These people also in turn inform and drive the development of new features or changes to the code base, like a waitress sharing dining feedback, and so are important parts in a successful code base.

So there you go, that’s a restaurant version of the web “stack.”  Each person and layer is integral to the process that creates a good website that evolves to meet its market and demand.  Now, I’m starving for food, there’s an app for that right.

jQuery Handling of CSS Classes

Though CSS3 transition animation support is still a little wonky, it’s getting better every day.  I’ve decided to pass all animation handling to CSS versus previously using jQuery’s fade functions.   jQuery is now simply the trigger, adding and removing classes.

Example: Fading Modal Box

A “modal window” is the technical term given to those annoying pop-ups in Windows.  It’s synonymous with dialog or alert.   In websites, the same concept is typically used to pop-up a larger version of a smaller image, as in a blog post.  For me, they’re useful as “page” content displays for websites which need to remain static, like in use of maps or dashboards.

jQuery

In the example below, a click listener handles the entire operation:

  • .modal-toggle is assigned to the button calling the action. ie: <a href=”#about” class=”.modal-toggle”>Click for About</a>
  • Of course, prevent default link action.
  • variable target references the href URL of the button or link. #about
  • This URL points to a div ID acting as my .modal. ie: <div id=”about”></div>
  • Next I add my “master” css class called .transitional to the .modal div.  I use a master class for applying CSS transition animations because obviously I don’t want to be adding this CSS to every single class that needs it — which increases browser load.
  • Now I’m using the link itself to judge if we’ve clicked on this before.
    • If the link has class active, then do the opposite first.  I don’t like testing negatives for if/else.
      • Remove class active, and remove class active on the modal.  Note we have to queue a delay to hide() a.k.a display: none because otherwise it won’t wait for the transition to finish. I set it to 500 ms ahead of my 400 ms.  See that hide() has a numeral hide(0) because this notifies jQuery to queue that operation; you could conceivably add more queued operations 1, 2, 3, etc.  This is required or delay does nothing.
    • If the link does not have it, let’s do our magic.
      • Add class active, then on the modal add class active.   Note we have to queue a delay on the addClass because otherwise the div will show() a.k.a. display: block immediately without waiting for the addClass.  The fancier queue function is used here because addClass cannot be queued itself.  So we have to nest it inside the available jQuery queue function.  dequeue() is required to again notify jQuery that addClass is a queued operation.   The delay is shorter, I’m just giving the browser time to separate the actions between show() and the addClass.
      • The animation is triggered by addClass(“active”) for the .modal div.
$(".modal-toggle").on("click", function(e) { 
        e.preventDefault();
	var target = $(this).attr("href");
	$(target).addClass("transitional");
	if ($(this).hasClass("active")) { 
		$(this).removeClass("active");
		$(target).removeClass("active").delay(500).hide(0);
	} else { 
		$(this).addClass("active");
		$(target).show().delay(10).queue(function(){
		    $(this).addClass("active").dequeue();
		});
	}
});

CSS

Simple enough!  The CSS is organized as follows:

  •  .modal creates our main control “layer”.  I’ve offset it from the top, assuming that’s where our main navigation link for .modal-toggle exists.  We don’t want to cover that up or we can’t close it.
  • .modal.active triggers our CSS animation to fade opacity to 100%.  That’s all it needs.
  • .content is an additional div layer nested under .modal because in general you should separate information out.  Also this lets you style the actual visible window as if it was centered on the page.
  • .transitional is my master CSS class.
.modal { 
	position: fixed;
	top: 5%;
	left: 0px;
	z-index: 1000;
	display: none;
	opacity: 0;
	width: 100%;
	height: 95%;
	}

.modal.active { 
	opacity: 1;
	}

.modal .content {
	position: relative;
	z-index: 200; 
	width: 80%; 
	height: 80%;
	margin: 0 auto 0 auto;
	background: #fff;
	padding: 20px;
	}

.transitional { 
    -webkit-transition: all 400ms ease-in;
    -moz-transition: all 400ms ease-in;
    -ms-transition: all 400ms ease-in;
    -o-transition: all 400ms ease-in;
    transition: all 400ms ease-in;
}

Get template name in WordPress

Generating the template name isn’t really a big deal, globally it’s available via echo get_option('current_page_template'). But in this case, when I was generating a slideshow of multiple pages, I needed to pass the slideshow query to it. So I had to write up my own for functions.php.


function get_template_name($query1) { 
	$template_name = get_post_meta( $query1->post->ID, '_wp_page_template', true ); 
	$length = strlen($template_name) - 4;
	if (strpos($template_name, '.php')) { 
		$template_name = substr($template_name, 0, $length);
		return $template_name;
	} else { 
		return $template_name;
	}
};

Call it after the while condition and it will generate the template name for each post (ie: echo get_template_name($query1)) The template name is stored like a simple meta value and includes the .php extension. So this will check for that to strip it out, otherwise will return ‘default.’

Why is this necessary for my slideshow? Well, some pages are to be laid out differently, this allows the CSS to make multiple slides of differing layouts.

Toggle Map Style and the Polygons Shown

In my previous Google Maps examples, I store all objects such as polygons and markers in an overlayArray.  Having a “global” theme change that doesn’t just alter the mapStyle, but also polygons is as simple as looping through your Array and setting options.   Here I’m using variable t1 to control the true/false variable, on a live site you should probably do something local such as adding a Class name to the button.

 

  var t1 = true;
    $("#toggle-theme").click(function(e) {
        e.preventDefault();
        if (t1) {
            t1 = false;
            map.setOptions({
                styles: mapstyleDefault
            });
            for (var i in overlayArray) {
                overlayArray[i].setOptions({
                    strokeColor: '#ff0000',
                    fillColor: '#ff0000',
                })
            }
        } else {
            t1 = true;
            map.setOptions({
                styles: mapstyleAlternate
            });
            for (var i in overlayArray) {
                overlayArray[i].setOptions({
                    strokeColor: '#29800b',
                    fillColor: '#29800b',
                })
            }
        }
    
    });

Remove Overlays

I find the most elegant way to deal with Google Maps objects from markers to polygons is to push them to a global array.  The simplest popular method is merely to use this array for clearing all objects.  The example below does that and references a separate InfoWindow array.  Simply setMap null, close the windows, and if needed reset all the arrays to 0.

function clearOverlays() {
    for (var i in overlayArray ) {
      overlayArray[i].setMap(null);
    }
    for (var i in infowinArray ) {
        infowinArray[i].close();
    }
    overlayArray.length = 0;
    infowinArray.length = 0;
};

Though this will suffice for simple loop operations where you basically call back and forth a few items, I found that for more complex objects and maps, a fancier robust function is needed to manage. In my case, I am storing a “complex” polyline, that is many polyline path segments which must be individually rendered.  For example if your path loops around a city, it’s clear you won’t be able to accomplish rendering that in one path.  KML notation already recognizes this and so groups many LineSegments into a MultiGeometry structure.  Manipulation of a KML layer’s stroke, color, etc is easy.  Unfortunately Google Maps does not have a multigeo, and using a Polygon object will not suffice as it automatically draws in the end points.  As well, your polylines may not necessarily connect but are associated with each other.

Here is my revised kitchen sink clear overlay function that offers a target and exclusion option.

  • clearOverlays(“all”) will simply result in everything being removed.
  • clearOverlays(20) or clearOverlays([20, 22, 25]) results in clearing only the targeted numbers being removed.
  • clearOverlays(“all”, 20) or clearOverlays(“all”, [20, 22, 25]) results in everything except the number or array being targeted.
  • Note you can’t do both such as clearOverlays(22, [80]), it will simply ignore the exclusion and go with the targeted item.  Of course this is also illogical.
  • The function takes into account, as in my case, whether you have an array within an array (“embedded”) as is required for grouping polylines or markers.
function clearOverlays(target, exclusion) { 

    // this function to go a level down into the array of objects (polylines, etc)
    function removeObj(a) { 
        if (typeof a[i].setMap == "function") { 
            for (var i in a) { 
                a[i].setMap(null);
            }
        }
    }

    if (target !== "all") { // just targeting something for removal

        if (typeof target == "number" || typeof target == "string") { 
            for (var i in overlayArray) { 
                if (overlayArray[i][0] == target) { removeObj(overlayArray[i][1]); }
            }
        } else { // if array

            for (var i in overlayArray) { 
                if (inArray(overlayArray[i][0], target)) { 

                    if (typeof overlayArray[i][1].setMap == "function") { 
                        overlayArray[i][1].setMap(null); 
                    } else { 
                        removeObj(overlayArray[i][1]);
                        }
                };
            };

        }

    } else { 

        if (exclusion == "") {  // target all, remove everything
            for (var i in overlayArray) { 
                if (typeof overlayArray[i][1].setMap == "function") { 
                    overlayArray[i][1].setMap(null); 
                    } 
                removeObj(overlayArray[i][1]);
                }
            } else { // target all but exclusions
            for (var i in overlayArray) { 
                if (inArray(overlayArray[i][0], exclusion)) { //ignore 
                } else {
                    removeObj(overlayArray[i][1]);
                    }
                }
            }
    };    

    function inArray(needle, haystack) { // needle being a string
        for (var i = 0; i < haystack.length; i++) {
            if (haystack[i] == needle) return true;
        }
        return false;
    }
};

 

Google Maps KML Toggle

My new KML toggle method is as follows which more logically lays out the variables and functions involved. The true improvement is that in order to add new KML files to the map, you simply add a new row to array kml. The code generates the rest. This code is literal easily adaptable to more asynchronous applications.

Code below or view it on Github.

<html>
<head>
<title>KML Toggle Example</title>

 <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>

 <script type="text/javascript">

    // define some variables to be used later
    var map;
    var overlays = [];
    var kml = {
        a: {
            name: "MPLS/STPL",
            url: "https://maps.google.com/maps/ms?authuser=0&vps=5&ie=UTF8&msa=0&output=kml&msid=212971981154994583939.0004b06640255267e038c"
        },
        b: {
            name: "Bicycling Tour Routes",
            url: "https://maps.google.com/maps/ms?authuser=0&vps=4&ie=UTF8&msa=0&output=kml&msid=212971981154994583939.0004902a1824bbc8c0fe9"
        }, 
    // keep adding more, the url can be any kml file
    };

    // initialize our goo
    function initializeMap() {
        var options = {
            center: new google.maps.LatLng(44.9812, -93.2687),
            zoom: 13,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        map = new google.maps.Map(document.getElementById("map_canvas"), options);

        createTogglers(); // in this example I dynamically create togglers, you can otherwise use jQuery
    };

    google.maps.event.addDomListener(window, 'load', initializeMap);

    // this does all the toggling work, id references the a b names I gave the kml array items

    function toggleKML(checked, id) {

        if (checked) {

            var layer = new google.maps.KmlLayer(kml[id].url, {
                preserveViewport: true,
                suppressInfoWindows: true 
            });

            kml[id].obj = layer; // turns the layer into an object for reference later
            kml[id].obj.setMap(map); // alternative to simply layer.setMap(map)
        }
        else {
            kml[id].obj.setMap(null);
            delete kml[id].obj;
        }

    };

    // in this example create the controls dynamically, prop is the id name 
    function createTogglers() {

        var html = "<form><ul>";
        for (var prop in kml) {
            html += "<li id="selector-" + prop + ""><input type='checkbox' id='" + prop + "'" +
            " onclick='highlight(this, "selector-" + prop + ""); toggleKML(this.checked, this.id)' />" +
            kml[prop].name + "</li>";
        }
        html += "<li class='control'><a href='#' onclick='removeAll();return false;'>" +
        "Remove all layers</a></li>" + 
        "</ul></form>";

        document.getElementById("toggle_box").innerHTML = html;
    };

    // easy way to remove all objects, cycle through the kml array and delete items that exist
    function removeAll() {
        for (var prop in kml) {
            if (kml[prop].obj) {
                document.getElementById("selector-" + prop).className = 'normal'; // in normal js, this replaces any existing classname
                   document.getElementById(prop).checked = false;
                kml[prop].obj.setMap(null);
                delete kml[prop].obj;
            }
        }
    };

    // append class on select, again old school way 
    function highlight(box, listitem) {
        var selected = 'selected';
        var unselected = 'normal';
        document.getElementById(listitem).className = (box.checked ? selected : unselected);
    };

 </script>

<style type="text/css">
#toggle_box { position: absolute; top: 100px; right: 30px; padding: 10px; background: #fff; z-index: 5; box-shadow: 0 5px 10px #777 }
ul { margin: 0; padding: 0; font: 100 1em/1em Helvetica; }
ul li { display: block; padding: 10px; margin: 2px 0 0 0; transition: all 100ms ease-in-out 600ms; }
ul li a:link { border: 1px solid #ccc; border-radius: 4px; box-shadow: inset 0 5px 20px #ddd; padding: 10px; font-size: 0.8em; display: block; text-align: center; }
.selected { font-weight: bold; background: #ddd; }
</style>

</head>
<body>
<div id="map_canvas" style="width: 100%; height: 600px;"></div>
<div id="toggle_box"></div>
</body>
</html>

Convert KML to PolyLine

To convert a KML file to a native Google Maps rendered polyline is essentially the process of parsing the KML, which is XML syntax, into its constituent parts, that being coordinates within a object.

I found the conversion necessary in the process of pulling stored KML data from a Google Fusion Table. If the KML data is stored as Location type, then it will return a MVCArray which can easily be picked apart with for loops to extract the coordinates. However, I have discovered that Fusion Tables has some issues or limitations with very complex KML objects that are not yielding all coordinate arrays, resulting in a half-rendered line. As such I’ve “manually” parsed the KML as a string. The two methods are presented.

success: function(data) {

var rows = data['rows'][0];

for (var i in rows) { 

var geo = rows[i]['geometries'];

	for (var j in geo) { 
	var linesegment = geo[j]['coordinates'];
	drawLine(linesegment);
	};

}


function drawLine(linesegment) { 
	var coordArray = [];
	console.log("rows");
	for (var i in linesegment) {
		var lat = linesegment[i][1];
		var lng = linesegment[i][0];
		var lineCoord = new google.maps.LatLng(lat, lng);
		coordArray.push(lineCoord);
	}

	var randomnumber = Math.floor(Math.random()*7);

	var colors = ["#FF0000", "#00ffff", "#FF00ff", "#Ffff00", "#555555", "#222222"];

  var routeLine = new google.maps.Polyline({
    path: coordArray,
    strokeColor: colors[randomnumber],
    strokeOpacity: 1.0,
    strokeWeight: 4,
  });

  routeLine.setMap(map);
  
}

Header Image via Featured Thumbnail

A lot of sites employ a header splash, notably photographer websites.  It is a highly requested feature of clients.  Fortunately WordPress has an easy hook with its featured image (thumbnail) setting that will allow an admin to set whatever image they wish for each post or page.  First, in functions.php, activate thumbnail support.

add_theme_support( ‘post-thumbnails’ );

Then in your theme file, such as header.php, call it forth.

<?php if (has_post_thumbnail( $post->ID ) ) : // is thumbnail set?
$image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), ‘single-post-thumbnail’ ); // grab image attr array ?>
<header class=”main-header” style=”background-image: url(‘<?php echo $image[0]; // the first array item is the src ?>’)”>
<?php else : ?>
<header class=”main-header” style=”background-image: url(‘<?php bloginfo(‘template_url’); // define a default in your theme folder ?>/images/defaultbg.jpg’)”>
<?php endif; ?>

Then CSS3’s background-size will do you well.   Alternatively you could have it echo into an img tag and set width, height 100% auto.

 

Thought Process of Working in Google Maps

Sometimes as a front-end you think by taking the “back-end” methodology route, you can accomplish great feats. In the end, the answer is often much simpler than you think. Such as in this example.

I need to find the coordinates of the center of a polygon.

Easy right?

First problem, the polygon is stored in KML format in a Fusion Table. Let’s use my awesome getJSON call from last year to retrieve the data, oh wait, the API has changed, okay let’s go to their ajax example even though it’s technically equivalent. Now the data is an object, oh I can’t work with an object.

Google, google, google…

Let’s try Google visualization since they enjoy offering different ways to find the same carrot. Oh okay I have to load Goog JS. More resources, the better! A dozen for loop iterations later, I still have an object.

Okay let’s try stringifying by manually pulling out the coordinate information from the KML object with js splits, parseFloats and jQ text() conversions. Great now I have 20 lines of coordinate data because it’s a complex polygon.

Except to retrieve the bounds of the polygon, I need a RECTANGLE. Argh! Perhaps if I become a zen master of algorithms, I can determine which four lines of coordinates are the approximate four corners of an averaged rectangle. Easy!

Google, google, google…

Try getCenter, getBounds and anything that gets something out of nothing. Thinking I need to extract the raw KML formatted data as is and then use to to call forth KmlLayer inline. Half an hour later, I realize I’m trying to thrust a packet of data into what is only a URL call.

Maybe I should extract the first coordinate point of each polygon via strlens and use that as an approximated marker location with some math adjustments. Oh wait, every polygon’s first coordinate point is all over the place. Banish the thought.

Google, google, google…

Answering some random questions on StackOverflow that do not relate but came up anyway.

Upon consulting every inch of Google Maps V3 developer guide, I come to realize I just need to zero in on the infoWindow’s self-centered latLng itself.

Several hours and dozens of lines of test code later, I actually needed just one line of code.

Yes sir, you can have labels in the middle of each polygon now.

/die.

Does Lean UX Replace Style Guides

Two years ago I read a great article by Smashing Magazine on “Style Guidelines for Brands and Websites” which suggests designers offer style guides to clients post-project. Often in the rush to the deadline, we forget that a website is never completely done and will continue to live on, organically changing and adapting itself. Having a style guide certainly gives the client evidence that actual strategic thought went into development of their brand. At the University of Minnesota, I became very familiar with their style guides during HTML 4.01’s reign. From a systematic organizational perspective, style guides were a doctrine that constrained specific uses but also allowed room for creativity in the spirit of the guide.

When I think about traditional style guides in the context of Lean UX, in reducing waste from iterative processes, I realize they are paradoxically outmoded and transgressed. Style guides can take many forms and for web often manifest in layout standards (wireframes) and graphic standards (color, shape, size, position). In essence a web style guide creates a prototype’s framework for you, and it’s up to you to fill in the pieces. In an ever evolving start-up environment, the visual standards are constantly changing, being thrown away or restructured into new forms. Why bother creating a guide when you know tomorrow even the very fundamental aspects of your product will change.

Now, at the same time, a style guide can act as a fundamental bedrock because it infuses the overall process with a sense of purpose and unity. Style guides come from the print environment where seemingly minor factors like line-height and line thickness can make or break. As we know from conceptual design or product design in general, that form is sometimes eminently more important than function (assuming the function is worthy). Twitter and Facebook are essentially communication mediums but their forms, in 140 characters or in dynamic multi-level posts, change the user experience. Mac OS X is a system that clearly has a style guide, that very specifically dictates every visual graphic to the point where outside developers and their designers must follow the edict. Ironically it is Windows that has shown a penchant for anything goes, and we know how that’s turned out.

Style guides are different from documentation. Jeff Gothelf writes in “Lean UX Is Not Anti-deliverable” (5/23/2012):

The focus should still be to design the best experience while minimizing the amount of time designing the wrong ones — not to design documentation that describes these design hypotheses.

Lean UX is about a specific design solution as a scientific question. Does my new app interface do what it intends without any instruction? The documentation outlining wireframes and hierarchy are what needs to go. On the other hand I see style guides as addressing a higher level question, whether the design communicates not just purpose but cohesion with the message, brand and experience. If anything, style guides answer questions of the strategic plan. The new Digg is perhaps the best example of a redesign that, one can argue, does exactly the same thing, but in form answers such a different mission statement.