Author Archive

Google Maps Toggle Mashup (outdated)

Update 12/30/12: This method is outdated and I have revised it.

Even I sometimes panic at the thought of acronyms but once you get past the technobabble, they’re just fancy names for simple concepts. “Keyhole Mashup Language” is the open source standard of mapping coordinates that Google adopted after it acquired the former Keyhole geo-mapping company. Like HTML, it involves semantic tags wrapping information. I was recently asked to fix a Google “mash-up” that involved multiple maps (KML layers) that would turn on and off a Google Map via Javascript. The fix solution was, as usual, to rebuild the whole thing using Google’s latest API standards (see samples here).

The basic application of this mash-up is to toggle multiple maps, hence the name. For my fellow urban planners, this allows the public to contrast and compare different layers like bike lanes, parks, and farmer markets without them needing to have any special ArcGIS viewer. Google also allows you to pull a KML layer directly off the Maps website, meaning you can pull live maps that anyone can update. For larger and more complex layers though you might want to have the KML layer on your server to reduce loading time.

The operating map is called the Big Box Tool Kit and features layers of points in the country where communities have opposed various big box corporations. Immediately one can toggle on maps to see how active certain parts of the country are compared to others.

Call the API.

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

Now in global.js or the header…

function initialize() {
 displayMaps();
}

Define attributes of the map (Google’s API controls and style guide is handy) and tell it where to show the Google map, in this case map_canvas.

  function displayMaps() {
	var myLatlng = new google.maps.LatLng(40,-93.8);
	var myOptions = {
	  zoom: 4,
	  center: (myLatlng),
	  mapTypeId: google.maps.MapTypeId.ROADMAP
	}

  	var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

In general the above should just generate the desired Google maps without anything on it. Now we finagle Javascript to output a layer if a form’s checkbox gets checked. There is an if statement for each layer you want. For example the first statement below: if checkbox fruit in formMapControl gets checked, layer1 will show a new Google map using apples.kml. Using form may not be terribly best practices, but the client wanted to use the browser’s native display of checkboxes.

  	if (document.formMapControl.fruit.checked) {

	        var layer1 = new google.maps.KmlLayer('apples.kml');
  		layer1.setMap(map);

  		/* Ensure the new layer does not change the map center or zoom */
  		layer1.set('preserveViewport', true);
	}

  	if (document.formMapControl.dairy.checked) {

  		var layer2 = new google.maps.KmlLayer('cheese.kml');
  		layer2.setMap(map);

  		layer2.set('preserveViewport', true);
	}

}/*this concludes function displayMaps*/
</script>

In the body the map “toggle control box” is the form and the Google map appears in a div called #map_canvas. Use CSS to style as appropriate. If you add checked to one or multiple inputs, it will default display that map layer when the page loads. In the client example link, the form is arranged in a list and position absolute next to the map_canvas, which is styled to be a box with display block. Options of course are endless, you could get fancier by giving the toggle box a transparent background and box-shadow, positioning it over the map. The bare basics follow.

<form name="formMapControl">
   
   <input type="checkbox" name="fruit" value="fruit" onclick="displayMaps();" checked />
      <label class="mapoption">Show Me Fruit!<label></li>
      <input type="checkbox" name="dairy" value="dairy" onclick="displayMaps();" />
      <label class="mapoption">Show Me Dairy!<label></li>

</form>

<div id="map_canvas"></div>

List Sub Categories of Parent Category

I just spent a good Friday resolving something that should be very simple. Of course it’s snowing like crazy so I’m not minding. On the Wake Magazine site I’ve been working on, we have a Blogs category that contains multiple sub categories. It’s a very newspaper-like site with multiple writers and thus multiple voices needing their own blog section. I wanted to list out all those sub categories anywhere in the blog area. I already addressed the magic (or insanity) of wp_list_categories so I won’t go there but my question was basically how do I call forth the parent category in a child category page? The solution was pieced together with some searching of the forums and uses a rare function cat_is_ancestor_of that I had no idea existed. Probably most WordPress run websites do not utilize the category terminology very deeply and so those issues are not often touched on. This solution also conditionally display only if you are on sub category page.

<?php
 foreach((get_the_category()) as $childcat) {
   $parentcat = $childcat->category_parent;
   if (cat_is_ancestor_of($parentcat, $childcat)) : ?>
     <div id="subnav">
     <h4>Insert a title or have it pulled from the parent cat</h4>
     <ul>
     <?php wp_list_categories('orderby=id&show_count=0&title_li=&child_of='.$parentcat); ?>
     </ul>
     </div>
   <?php endif; 
   } ?>

Super Simple Random Image

This super simple piece of PHP code will randomly pull images from a folder that are numbered (ie: 1 through 9).  Technically it’s just any folder with numbered image names.   For TCS I created a folder called gallery in my theme folder and placed images in it 1.jpg, 2.jpg and so forth.

<?php
// Change this to the total number of images in the folder
$total = "9";
// Change to the type of files to use eg. .jpg or .gif
$file_type = ".jpg";
// Change to the location of the folder containing the images
$image_folder = "gallery";
// You do not need to edit below this line
$start = "1";
$random = mt_rand($start, $total);
$image_name = $random . $file_type; ?>

Next this echo will call forth the two locations.

<?php echo "$image_folder/$image_name"; ?>

I actually integrated this into the background CSS to produce a cool random background image effect for the header.

<div id="header" style="background: url('<?php bloginfo('template_directory'); ?>/<?php echo "$image_folder/$image_name"; ?>') center top no-repeat">

Exclude Categories from Post Categories List

The exclude variable in the stand-alone wp_list_categories doesn’t exist for get_the_category when your blog is listing the categories related to that post. So you have to create a custom function to define the categories which output. I found the solution at Technokinetics and adapted it here. Another blog also covers the topic (of course you can define cat_ID instead of cat_name).

Put in your theme. Btw the (‘, ‘) is a separator you can change that will go between the categories.

<span><?php custom_cat_list(', '); ?></span>

Put in functions.php, note the function below uses an && AND operator.

function custom_cat_list($separator) {
      $first_time = 1;
      foreach((get_the_category()) as $category) {
        if ($category->cat_name != 'Music' && $category->cat_name != 'Hipsters') {
          if ($first_time == 1) {
            echo '<a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>'  . $category->name.'</a>';
            $first_time = 0;
          } else {
            echo ' I don't like music or hipsters or you could just leave this blank. ';
          }
        }
      }
    }

Super Simple Featured Box

I’m using this function because I recently created a featured box for TwinCityScene and would like control over its structure.  While the built-in sticky option could suffice for simple CSS sizing, it doesn’t really let me do much with say thumbnails.  I also prefer not to use a heavy plug-in which then we get into the arena of ranking featured posts when honestly I want to keep this site automated.

To do this box, I create a new category called “Featured.” This is an administrative category being merely functional. However I still want to list the post categories that the featured post belongs to (ie: “Music,” “Art”).  So in my index.php (or applicable theme file) I called the loop twice.  In the first I told query_posts to show only 1 post from category 684 which happens to be the new Featured cat.  then the second loop query_posts omits 684 with a negative – sign.   I’m sure there are other ways to customize the loop but I found this to be the most efficient and natural for WordPress instead of a litany of if else statements.

<?php query_posts("showposts=1&cat=684"); ?>
<?php while ( have_posts() ) : the_post() ?>
My structure for the featured box where I used <?php custom_cat_list(', '); ?> to omit the Featured Category from showing up.
<?php endwhile ?>

<?php query_posts("cat=-684"); ?>
<?php while ( have_posts() ) : the_post() ?>
My structure for regular posts where get_the_category lists normally.
<?php endwhile ?>

Integrate Links Into Navigation

If you are using wp_list_categories sometimes you want to manually add HTML/links before and after the categories that are generated in order to preserve the ul list. Similarly, you’d want to bundle the ul tags within an if else statement. Most PHP gurus know this but basically you can use an echo output to generate the needed HTML. I used this for TwinCityScene in adding a home link to the front and social networking buttons to the end. Why would you want to go to the hassle to do this? Accessibility! Special browsers will love you for logically grouping all your links into one ul nav.

<?php 
global $post; 
echo '<ul class="catnav"><li class="cat-item homelink"><a href="/">Home</a>'; 
wp_list_categories('orderby=name&amp;title_li='); 
echo '</li> 
<li class="socnet iconrss"><a title="RSS Feed" href="rss.xml">RSS Feed</a></li> 
<li class="socnet icontw"><a title="Twitter@TwinCityScene" href="https://www.twitter.com/twincityscene">Twitter</a></li> 
<li class="socnet iconfb"><a title="Facebook Fan Page" href="https://www.facebook.com/twincityscene">Facebook</a></li> 
'; } 
else { }; 
?>

The attached CSS follows. Of course it’s a bit gussied up but the main elements are there.

.catnav { background: #000 url('images/bgnav.png') center top no-repeat; clear: both; list-style: none; margin: 0; padding: 0; border-bottom: 1px solid #111; border-top: 1px solid #111; width: 100%; display: block; height: 35px; text-align: center;}
.catnav li.cat-item { color: #555; display: inline; text-align: left; margin: 0 5px 0 0; padding: 10px 0 10px 2px;}
.catnav li.cat-item a { text-shadow: 1px 1px #333; text-transform: uppercase; padding: 0 7px 0 7px; height: 35px; color: #ccc; border-right: 1px solid #333; font: 300 1.3em Helvetica, Arial, sans-serif; letter-spacing: -0.5px; line-height: 1.9em; }
.catnav li:hover a, .catnav li a:hover { text-shadow: 1px 1px #333; color: #fff; text-decoration: underline;}
.catnav li:hover { color: #fff; background: transparent url('images/bghover.png') center top no-repeat;}
.catnav li.homelink { color: #000;}
.catnav li.homelink a { padding-left: 5px; border-left: none; }
.catnav li.homelink:hover a { color: #fff;}

.catnav li.socnet { border: none; float: right; margin: 0 10px 0 10px; padding: 0;}
.catnav li.socnet a { margin: 2px 0 0 0; width: 30px; height: 30px; display: block; text-indent: -999em;}
.catnav li.icontw a { background: transparent url('images/twitter.png') center center no-repeat; }
.catnav li.iconfb a { background: transparent url('images/facebook.png') center center no-repeat; }
.catnav li.iconrss a { background: transparent url('images/rss.png') center center no-repeat; }