<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Codethink &#187; javascript</title>
	<atom:link href="https://codethink.no-ip.org/posts/coding/javascript/feed" rel="self" type="application/rss+xml" />
	<link>https://codethink.no-ip.org</link>
	<description>A blog about coding, life, and other arbitrary topics</description>
	<lastBuildDate>Sun, 15 Mar 2026 21:30:15 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=4.1.29</generator>
	<item>
		<title>[JavaScript] Finding Equidistant Lat/Long Coordinates</title>
		<link>https://codethink.no-ip.org/archives/746</link>
		<comments>https://codethink.no-ip.org/archives/746#comments</comments>
		<pubDate>Sat, 03 Dec 2011 08:17:52 +0000</pubDate>
		<dc:creator><![CDATA[aroth]]></dc:creator>
				<category><![CDATA[coding]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[hack]]></category>
		<category><![CDATA[location]]></category>
		<category><![CDATA[maps]]></category>

		<guid isPermaLink="false">http://codethink.no-ip.org/wordpress/?p=746</guid>
		<description><![CDATA[Here&#8217;s a quick one that was inspired by a StackOverflow question and built using the references posted here. It allows you to compute the position of an arbitrary number of points (expressed as latitude/longitude pairs) equidistant from a given centerpoint &#8230; <a href="https://codethink.no-ip.org/archives/746">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Here&#8217;s a quick one that was inspired by a <a href="http://stackoverflow.com/questions/6789992/need-to-find-lats-long-of-a-location-which-is-about-50km-away-from-a-location" target="_blank">StackOverflow question</a> and built using the references posted <a href="http://www.movable-type.co.uk/scripts/latlong.html" target="_blank">here</a>.  It allows you to compute the position of an arbitrary number of points (expressed as latitude/longitude pairs) equidistant from a given centerpoint (using a given radius/distance, of course) on the surface of the Earth.  The crux of the code goes like so:</p>
<pre class="brush: jscript; title: ; notranslate">window.pointsAround = function(centerLat, centerLng, radius, numInterpolations) {
    var result = [];

    //do annoying trig maths to work out the delta in latitude between our start and end points
    var targetD = radius;          //km
    var fractionalDistance = (targetD / radiusOfEarth) / 2;
    var sqrtA = Math.sin(fractionalDistance);
    var a = sqrtA * sqrtA;
    var sinHalfDLat = Math.sqrt(a);
    var dLat = Math.asin(sinHalfDLat) * 2;
    var dLatDegrees = degrees(dLat);
    
    var minLat = centerLat - dLatDegrees;              //furthest valid latitude above the origin
    var maxLat = centerLat + dLatDegrees;            //furthest valid latitude below the origin
    
    var centerLatRadians = radians(centerLat); 
    
    //topmost and bottommost points in the circle
    result.push({lat: minLat, lng: centerLng});
    result.push({lat: maxLat, lng: centerLng});
    
    //step from minLat to maxLat, interpolating coordinates that lie upon the circle
    numInterpolations = numInterpolations ? numInterpolations : 360;
    var step = (maxLat - minLat) / (numInterpolations / 2.0);
    for (var count = 0; count &lt; (numInterpolations / 2) - 1; count++) {
        minLat += step;
        var minLatRadians = radians(minLat);
        dLat = radians(centerLat - minLat);
        
        //more annoying trig to work out the delta in longitude for our interpolated coordinate
        var dLon = 2 * Math.asin(Math.sqrt((a - (Math.sin(dLat/2) * Math.sin(dLat/2))) / (Math.cos(minLatRadians) * Math.cos(centerLatRadians))));
        var dLonDegrees = degrees(dLon);
        
        var newLng = centerLng + dLonDegrees;
        var deltaLng = newLng - centerLng;
        result.push({lat: minLat, lng: newLng});
        result.push({lat: minLat, lng: centerLng - deltaLng});
    }
    
    return result;
};</pre>
<p>This code works out the northernmost and southernmost points that are the specified distance away from the given centerpoint.  It then steps between the minimum and maximum latitude of these two points, interpolating the appropriate longitudinal value(s) to satisfy the equidistant constraint.  The total number of coordinates returned can be controlled using the optional &#8216;<em>numInterpolations</em>&#8216; parameter.  When not specified a total of 360 points will be returned by default, because that is a nice, round number.</p>
<p>If you use something like the following code to plot some points on a map:</p>
<pre class="brush: jscript; title: ; notranslate">window.map = new GMap2(document.getElementById(&quot;mapDiv&quot;));
    var centerPoint = new GLatLng(37.4419, -122.1419);
    map.setCenter(centerPoint, 8);
    map.addControl(new GLargeMapControl3D());
    map.addControl(new GMapTypeControl());
    
    var marker = new GMarker(centerPoint);
    var markerText = &quot;Center @ 37.4419, -122.1419&quot;;
    GEvent.addListener(marker, &quot;click&quot;, markerClickHandler(marker, markerText));
    map.addOverlay(marker);
    
    var points = pointsAround(37.4419, -122.1419, 50);
    for (var index = 0; index &lt; points.length; index++) {
        var point = points[index];
        var latlng = new GLatLng(point.lat, point.lng);
        marker = new GMarker(latlng);
        markerText = &quot;Marker @ &quot; + point.lat + &quot;, &quot; + point.lng;
        GEvent.addListener(marker, &quot;click&quot;, markerClickHandler(marker, markerText));
        map.addOverlay(marker);
    }</pre>
<p>&#8230;you will get a nice circle of points around the hard-coded centerpoint.  You can see a working example of this here:  <a href="http://jsfiddle.net/HmchC/27/" target="_blank">http://jsfiddle.net/HmchC/27/</a>.</p>
]]></content:encoded>
			<wfw:commentRss>https://codethink.no-ip.org/archives/746/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>[JavaScript] Creating an Animated Hurricane Tracker</title>
		<link>https://codethink.no-ip.org/archives/773</link>
		<comments>https://codethink.no-ip.org/archives/773#comments</comments>
		<pubDate>Sat, 10 Sep 2011 15:09:21 +0000</pubDate>
		<dc:creator><![CDATA[aroth]]></dc:creator>
				<category><![CDATA[coding]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[hack]]></category>

		<guid isPermaLink="false">http://codethink.no-ip.org/wordpress/?p=773</guid>
		<description><![CDATA[Here&#8217;s a fun little diversion I came up with when the news was all abuzz with information about Hurricane Irene. Now I use Wikipedia almost exclusively for keeping track of this sort of thing as I find that it consistently &#8230; <a href="https://codethink.no-ip.org/archives/773">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Here&#8217;s a fun little diversion I came up with when the news was all abuzz with information about <a href="http://en.wikipedia.org/wiki/Hurricane_Irene_(2011)" target="_blank">Hurricane Irene</a>.  Now I use Wikipedia almost exclusively for keeping track of this sort of thing as I find that it consistently provides the most up to date data in the cleanest and most easy to digest format, but I also noticed a large volume of comments on other news sites complaining about the accuracy of hurricane forecasting.  And this got me to wondering, just how accurate are the historical forecasts when overlaid with the actual storm track?</p>
<p>Well Wikipedia doesn&#8217;t provide this information directly, but interestingly enough Wikipedia does in fact keep all the <a href="http://en.wikipedia.org/w/index.php?title=File:09L_2011_5day.gif&#038;limit=500#filehistory" target="_blank">historical data</a> necessary to answer this question.  Thanks to Chrome&#8217;s awesome JavaScript console (and the fact that Wikipedia uses jQuery on all of its pages) it is a very simple matter to extract this historical information in a format that is easy to work with later.  The following code will do the trick:</p>
<pre class="brush: jscript; title: ; notranslate">var result = []; 
jQuery.each($(&quot;.filehistory a[href$=5day.gif]&quot;), function(){
    result.push(this.href)
}); 
result;</pre>
<p>This simply constructs an array containing the URL&#8217;s of every historical forecast/storm track graphic (ordered by date from newest to oldest) and outputs it to the console.  We can then copy/paste the console output to wherever we like, such as <a href="http://jsfiddle.net" target="_blank">jsFiddle</a> for instance.  Combine this with some basic HTML structure:</p>
<pre class="brush: xml; title: ; notranslate">&lt;div class=&quot;title&quot;&gt;
    Hurricane Irene Animated Forecast Map
&lt;/div&gt;
&lt;img id=&quot;display&quot; src=&quot;http://fcf.teambeachbody.com/fcf/images/spinner5.gif&quot; /&gt;
&lt;div id=&quot;status&quot;&gt;
    (&lt;span id=&quot;numLoaded&quot;&gt;&lt;/span&gt; of &lt;span id=&quot;total&quot;&gt;&lt;/span&gt; frames loaded)
&lt;/div&gt;</pre>
<p>&#8230;and some simple JavaScript to handle the actual rendering:</p>
<pre class="brush: jscript; title: ; notranslate">document.getElementById(&quot;numLoaded&quot;).innerHTML = &quot;0&quot;;
document.getElementById(&quot;total&quot;).innerHTML = data.length;

//preload all the images so that they are cached for the animation
window.imagesLoaded = 0;
for (var index = data.length - 1; index &gt;= 0; index--) {
    var node = document.createElement(&quot;img&quot;);
    node.style.display = &quot;none&quot;;
    document.body.appendChild(node);
    $(node).bind('load', function() {  
        window.imagesLoaded++;  
    });
    $(node).attr('src', data[index]);
    //node.src = data[index];
}

//run the animation
window.currentImage = data.length - 1;
window.updateAnimation = function() {
    if (window.imagesLoaded &lt; data.length) {
        //keep waiting
        document.getElementById(&quot;numLoaded&quot;).innerHTML = window.imagesLoaded;
        return;
    }
    $(&quot;#status&quot;).hide();
    document.getElementById(&quot;display&quot;).src = data[currentImage];
    currentImage--;
    if (currentImage &lt; 0) {
        currentImage = data.length - 1;
    }
};

setInterval(updateAnimation, 200);</pre>
<p>&#8230;and you get an animated map of the entire forecast history, including the actual storm track.  The result looks something like this:</p>
<p><iframe src="http://fiddle.jshell.net/TqmVg/6/show/" width="425" height="380" frameBorder="0"><br />
</iframe></p>
<p>Not too bad for a few dozen lines of code and about 30 minutes worth of effort.  You can also access a full-scale, editable version of this animated storm history <a href="http://jsfiddle.net/TqmVg/5/" target="_blank">here</a>.</p>
<p>So what does this say about the accuracy of the hurricane forecasting for Irene?  Personally I think it shows that the forecasts are pretty damn accurate.  In fact, if you focus just on the solid white portion of the predicted storm track it appears that the storm never deviates from its forecast path.  It&#8217;s only when looking at the dashed white portion of the forecast that any significant deviation can be noted.  And the dashed white portion indicates forecasts that are more than 72 hours in the future.  </p>
<p>Of course we should always be working to improve our ability to predict and forecast these things, but I have to think that being able to accurately predict a storm&#8217;s movement for up to 72 hours into the future is adequate for most purposes.</p>
]]></content:encoded>
			<wfw:commentRss>https://codethink.no-ip.org/archives/773/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>[JavaScript] Naming Your Function &#8216;$&#8217; is not Clever</title>
		<link>https://codethink.no-ip.org/archives/720</link>
		<comments>https://codethink.no-ip.org/archives/720#comments</comments>
		<pubDate>Sat, 16 Jul 2011 10:44:26 +0000</pubDate>
		<dc:creator><![CDATA[aroth]]></dc:creator>
				<category><![CDATA[coding]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[rant]]></category>

		<guid isPermaLink="false">http://codethink.no-ip.org/wordpress/?p=720</guid>
		<description><![CDATA[The atrocity that is the dollar function dates back at least 2005 and the introduction of the Prototype Framework. Back in those days, &#8216;$()&#8216; was simply a shorthand way of saying &#8216;document.getElementById()&#8216; without having to type all 24 characters. And &#8230; <a href="https://codethink.no-ip.org/archives/720">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>The atrocity that is the dollar function dates back at least 2005 and the introduction of the <a href="http://en.wikipedia.org/wiki/Prototype_JavaScript_Framework" target="_blank">Prototype Framework</a>.  Back in those days, &#8216;<em>$()</em>&#8216; was simply a shorthand way of saying &#8216;<em>document.getElementById()</em>&#8216; without having to type all 24 characters.  And don&#8217;t get me wrong, aliasing &#8216;document.getElementById&#8217; to something shorter is not a bad idea, in and of itself.  But why should &#8216;<em>$()</em>&#8216; be the alias?  Such a name gives no clue that the function is looking up a DOM element by its id.  Something like &#8216;<em>findById()</em>&#8216; (or even &#8216;<em>$findById()</em>&#8216; if there are concerns about naming collissions) would have been infinitely more clear, and still a good deal shorter than writing &#8216;<em>document.getElementById()</em>&#8216;.  </p>
<p>But sadly, Prototype decided to use &#8216;<em>$()</em>&#8216; as the name of their alias.  And even worse, other frameworks have followed in this pattern, adding their own dollar functions that have semantics that can be completely different from the original &#8216;<em>$()</em>&#8216; introduced by Prototype.  Consider <a href="http://en.wikipedia.org/wiki/Jquery" target="_blank">jQuery</a>, which introduces its own version of &#8216;<em>$()</em>&#8216; which can be used to find (and wrap and clone) elements in the DOM by a number of different criteria, but which sadly fails miserably when given a string containing a literal element id.  This creates a lovely situation where now the developer cannot even guess at what &#8216;<em>$()</em>&#8216; is actually doing without first checking to see which framework is being used by the code.  It also means that any code that was written using Prototype&#8217;s &#8216;<em>$()</em>&#8216; will be broken by including jQuery (and vice-versa).  </p>
<p>&#8220;But that&#8217;s what &#8216;<em><a href="http://api.jquery.com/jQuery.noConflict/" target="_blank">jQuery.noConflict()</a></em>&#8216; is for&#8221;, you say.  But you miss the point.  It shouldn&#8217;t be necessary for &#8216;<em>jQuery.noConflict()</em>&#8216; to exist in the first place.  If the jQuery developers hadn&#8217;t decided that it would be cute to define their own version of &#8216;<em>$()</em>&#8216;, then jQuery would never conflict with anything except possibly an older version of jQuery.  The thing that really baffles me is how so many developers (obviously talented developers, at that, considering the work that goes into something like Prototype or jQuery) can all decide that it is a good idea to try to lay claim to a name that exists in the global scope.  Granted JavaScript does not have any concept of a proper namespace, but if jQuery limited itself to only setting properties on an object named &#8220;jQuery&#8221; and Prototype did the same on an object named &#8220;Prototype&#8221; and so on, the current JavaScript landscape would look ever so much more sane.</p>
<p>And of course, this says nothing of the &#8216;<em>$$()</em>&#8216; and &#8216;<em>$F()</em>&#8216; functions that were also introduced by Prototype (and the &#8216;$E()&#8217; and &#8216;$ES()&#8217; functions inexplicibly introduced by <a href="http://solutoire.com/2007/09/20/understanding-mootools-selectors-e-and-es/" target="_blank">MooTools</a>) and whose names are so semantically worthless that a developer has no hope of inferring their function without consulting the reference documentation.  Which again can only be accomplished after checking the entire codebase to determine which framework it is that is defining these functions with its woefully awful naming convention.</p>
<p>If the developers of Prototype, jQuery, Mootools, and the like wanted to turn JavaScript into an unreadable and unmaintainable mess of a language like <a href="http://en.wikipedia.org/wiki/Perl_language_structure" target="_blank">Perl</a>, then I applaud them for their efforts.  But if not then I call them all out on their atrocious naming convention and design decisions.  There is no excuse for this nonsense.  If you&#8217;re building a JavaScript library or framework, then pick a reasonable &#8220;namespace&#8221; to use for it.  This namespace should be the only thing that you bind in the global scope.  Everything else that is part of your library should be bound as a property inside of this namespace.  And there should be no automatic creation of shorthand aliases in the global scope.  </p>
<p>I don&#8217;t think this is too much to ask.  And of course, any developer that wants to use a global shorthand alias can always do:</p>
<pre class="brush: jscript; title: ; notranslate">window.$J = jQuery;
window.$P = Prototype.$;  //or:  window.$P = document.getElementById;</pre>
<p>It takes all of one line of code to set up an alias.  But when you start doing this automatically for everyone that uses your framework you create nothing but problems.  Especially when you jump on the bandwagon and choose the same crappy shorthand alias names that other frameworks are already using.</p>
<p>There is absolutely no reason why multiple JavaScript frameworks should all be competing over the same terrible function names.  This isn&#8217;t a contest to see who can break the most legacy code, or who can come up with the most obtuse API.  <a href="http://en.wikipedia.org/wiki/International_Obfuscated_C_Code_Contest" target="_blank">They do have such contests</a> if you are interested in such a thing, but this is not one of them.  The only thing accomplished by parading the dollar sign around as an example of a well-chosen function name is an increased brittleness in the code that glues together the majority of our modern websites.  It muddies semantics, and creates cases where completely unrelated libraries are not easily compatible with each other, and where simply importing a new library can cause existing code to break.  Even worse, some novice developers get the wrong idea from all those dollar signs flying around think that they need to (or should) prefix all of their function names with &#8220;$&#8221;.  So let&#8217;s put this bad practice to bed before it&#8217;s too late.</p>
<p>So please, can well all stop writing frameworks that give people the impression that calling a function &#8220;$&#8221;, &#8220;$$&#8221;, &#8220;$ES&#8221;, or &#8220;$anything&#8221; is a good idea?  Is it so difficult to choose a reasonable namespace, minimize the number of things that you declare in the global scope, and allow the developer to define a global shorthand alias for this-or-that utility function if they decide they want to?  I think not.</p>
]]></content:encoded>
			<wfw:commentRss>https://codethink.no-ip.org/archives/720/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Introducing Webcomix</title>
		<link>https://codethink.no-ip.org/archives/511</link>
		<comments>https://codethink.no-ip.org/archives/511#comments</comments>
		<pubDate>Sat, 19 Mar 2011 07:15:12 +0000</pubDate>
		<dc:creator><![CDATA[aroth]]></dc:creator>
				<category><![CDATA[banter]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[software]]></category>
		<category><![CDATA[media]]></category>
		<category><![CDATA[random]]></category>

		<guid isPermaLink="false">http://codethink.no-ip.org/wordpress/?p=511</guid>
		<description><![CDATA[I wanted to take a brief moment to invite anyone who stumbles across this post to beta-test my latest personal project; Webcomix. Webcomix is a simple web-comic aggregation service that allows you to read a number of different comics on &#8230; <a href="https://codethink.no-ip.org/archives/511">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>I wanted to take a brief moment to invite anyone who stumbles across this post to beta-test my latest personal project; <a href="http://webcomix.no-ip.org" target="_blank">Webcomix</a>.  Webcomix is a simple web-comic aggregation service that allows you to read a number of different comics on a single page.  Here is a screenshot of it in action:</p>
<p><a href="http://codethink.no-ip.org/wordpress/wp-content/uploads/2011/03/webcomix.png" rel="lightbox[511]"><img src="http://codethink.no-ip.org/wordpress/wp-content/uploads/2011/03/webcomix-1200x681.png" alt="Webcomix screenshot" title="Webcomix screenshot" width="640" height="363" class="aligncenter size-large wp-image-512" /></a></p>
<p>Each comic in Webcomix is periodically checked for updates, so if like me you keep tabs on several different web-comics that all update at different intervals then Webcomix will save you from having to remember to refresh half a dozen different websites at various times just to keep up to date.  Simply visit your Webcomix dashboard and you&#8217;re set!</p>
<p>Underneath the covers there&#8217;s a fair bit that I&#8217;m proud of with this app.  First off the entire system is designed to be as lightweight and efficient (in terms of server compute-time and bandwidth) as reasonably possible.  Virtually all of the actual work is handled by the client-side JavaScript.  The handful of tasks that must be performed server-side are optimized with the help of a custom caching layer which ensures that any given computation (or fetch of an external resource) only needs to be performed once.  There is also an additional caching layer in the client used to prevent it from making any given request to the server more than once per session.  </p>
<p>The server itself is client-agnostic and provides a simple JSON-based API, meaning that while the initial incarnation of Webcomix is in the form of a web-app it should be just as easy to package the same functionality in a mobile, desktop, or other flavor of application.  But that&#8217;s a project for another day.</p>
<p>Anyhow, please note that Webcomix should be considered to be beta software at the moment.  So if you find any bugs or have any suggestions for new features or improved functionality then please don&#8217;t hesitate to say so in the comments section.  </p>
<p>Also, the list of comics currently available in Webcomix is not set in stone and is only based upon my personal preferences at the moment.  Webcomix is designed in a way that makes adding additional comics a trivial task, so if your favorite comic is currently not in the list then I encourage you to post a request in the comments section so that I can add it.  </p>
<p>Lastly, if anyone has any good ideas for how to extend the comic selection UI to handle a large number of comics that they&#8217;d like to share, then please do.  The current interface with its basic rows of checkboxes is obviously not sufficient for handling hundreds (or even dozens) of comics.  It needs to be replaced with something better (or at least, collapsible) soon.</p>
]]></content:encoded>
			<wfw:commentRss>https://codethink.no-ip.org/archives/511/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>[JavaScript + CSS] Fun with Google Maps</title>
		<link>https://codethink.no-ip.org/archives/472</link>
		<comments>https://codethink.no-ip.org/archives/472#comments</comments>
		<pubDate>Fri, 11 Mar 2011 13:06:01 +0000</pubDate>
		<dc:creator><![CDATA[aroth]]></dc:creator>
				<category><![CDATA[coding]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[hack]]></category>

		<guid isPermaLink="false">http://codethink.no-ip.org/wordpress/?p=472</guid>
		<description><![CDATA[Here are a couple of quick Google Maps hacks that I came up with quite awhile ago; several years ago, in fact. While not hugely useful or profound, they do expose some fairly large holes in the Google Maps API. &#8230; <a href="https://codethink.no-ip.org/archives/472">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Here are a couple of quick Google Maps hacks that I came up with quite awhile ago; several years ago, in fact.  While not hugely useful or profound, they do expose some fairly large holes in the Google Maps API.  Holes that I would have expected a company like Google to have patched up by now.  </p>
<p>First, let&#8217;s say that for whatever reason you need to remove the &#8220;Powered by Google&#8221; logo and the other copyright and similar boilerplate that normally appears along the bottom of the map.  Why would you want to do this?  Perhaps because you are displaying your map inside of a small area of the page where space is constrained to the point that the logo and other things are adding too much noise.  Or perhaps because you feel (quite justifiably) that Google Maps have become iconic to the point that nobody needs to see a &#8220;Powered by Google&#8221; logo in the corner to know that the map is being powered by Google.  </p>
<p>Whatever your reason for wanting to unclutter the map&#8217;s footer section, the task can be accomplished using a smidgen of CSS:</p>
<pre class="brush: css; title: ; notranslate">		.terms-of-use-link {
		    display: none;
		}

		#myMapContainerId div span {
			display: none;
		}</pre>
<p>&#8230;and a handful of JavaScript:</p>
<pre class="brush: jscript; title: ; notranslate">			//call this after setting up your GMap2 instance
			window.unclutter = function() {
				var executed = false;
				var images = document.getElementsByTagName('img');
				for (var index = 0; index &lt; images.length; index++) {
					var node = images[index];
					if (node.src &amp;&amp; node.src.indexOf(&quot;mapfiles/poweredby.png&quot;) &gt; 0) {
						node.style.display = 'none';
						executed = true;
					}
				}

				if (! executed) {
					setTimeout(window.unclutter, 250);
				}
			};</pre>
<p>It&#8217;s pretty straightforward, really.  The CSS gets rid of the &#8220;Terms of Use&#8221; link, as well as the spans that are used to display copyright text (note that you should replace the &#8216;<em>myMapContainerId</em>&#8216; with whatever your actual map div-id is).  The JavaScript is used to get rid of the &#8220;Powered by Google&#8221; logo, which is added to the map after it loads.  To use this code, you just need to call &#8216;<em>unclutter()</em>&#8216; after setting up your Google Map instance.</p>
<p>Of course, doing this is a blatant violation of the Google Maps Terms of Service.  You know, the terms Google made you agree to when you generated your API key.  Whether or not there is any merit in having Terms of Service mandate things which do nothing whatsoever to benefit end users such as the display of logos and copyright gibberish is a topic for another day.  The topic for today is, if Google Maps can be used without an API key, and hence without agreeing to the Terms of Service, what does it matter what the terms are anyways?  </p>
<p>That&#8217;s right, the Google Maps API can be used, at least for basic tasks, completely without an API key.  It&#8217;s quite simple really, just a tiny bit more JavaScript:</p>
<pre class="brush: jscript; title: ; notranslate">			//be sure to do this *before* you source in the Google Maps javascript
			window._alert = window.alert;
			window.alert = function() {return;};</pre>
<p>&#8230;and then you can include the Google Maps JavaScript without specifying an API key, like so:</p>
<pre class="brush: xml; title: ; notranslate">&lt;script src=&quot;http://maps.google.com/maps?file=api&amp;amp;v=2&amp;amp;sensor=true&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;</pre>
<p>The added JavaScript simply moves the browser&#8217;s built-in &#8216;<em>alert()</em>&#8216; function to &#8216;<em>_alert()</em>&#8216; so that the map can&#8217;t use it to display a message complaining about the missing API key.  For whatever reason, apart from this alert message Google does nothing to prevent their API from being used without a valid key.  So by simply suppressing the error message you can get a fully functional Google map without registering for a key or agreeing to the Terms of Service.</p>
<p>Put all of this together and you can get an anonymous, unbranded, uncluttered map the works just as well as the original version.  The source code (verified in current versions of IE, Firefox, and Chrome) might look something like this:</p>
<pre class="brush: xml; title: ; notranslate">&lt;html&gt;
	&lt;head&gt;
		&lt;title&gt;Google Maps API Example Hack&lt;/title&gt;
		&lt;style&gt;
			.terms-of-use-link {
		    		display: none;
			}

			#myMapContainerId div span {
			     display: none;
			}
		&lt;/style&gt;
		&lt;script type=&quot;text/javascript&quot;&gt;
			window._alert = window.alert;
			window.alert = function() {return;};

			window.setupMap = function() {
				window.map = new GMap2(document.getElementById(&quot;myMapContainerId&quot;));
				map.setCenter(new GLatLng(37.4419, -122.1419), 13);
				map.addControl(new GLargeMapControl3D());
				map.addControl(new GMapTypeControl());
			};

			window.unclutter = function() {
				var executed = false;
				var images = document.getElementsByTagName('img');
				for (var index = 0; index &lt; images.length; index++) {
					var node = images[index];
					if (node.src &amp;&amp; node.src.indexOf(&quot;mapfiles/poweredby.png&quot;) &gt; 0) {
						node.style.display = 'none';
						executed = true;
					}
				}

				if (! executed) {
					setTimeout(window.unclutter, 250);
				}
			};

			window.onload = function() {setupMap(); unclutter();};
		&lt;/script&gt;
		&lt;script src=&quot;http://maps.google.com/maps?file=api&amp;amp;v=2&amp;amp;sensor=true&amp;amp;&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
	&lt;/head&gt;
	&lt;body&gt;
		Note the lack of branding/logos, terms of use links, and copyright footer text in the map below.&lt;br /&gt;
		Also note the lack of any Google Maps API key in the document source.&lt;br /&gt;
		And the lack of any annoying &lt;a href=&quot;#&quot; onclick=&quot;_alert('I can still create alerts, but the Google Map can\'t.'); return false;&quot;&gt;alert&lt;/a&gt; popups complaining about the API key.&lt;br /&gt;&lt;br /&gt;
		&lt;div id=&quot;myMapContainerId&quot; style=&quot;width: 600px; height: 400px;&quot;&gt;&lt;/div&gt;
	&lt;/body&gt;
&lt;/html&gt;</pre>
<p>&#8230;which gives you a page like <a href="http://codethink.no-ip.org/mapHacks.html" target="_blank">this one</a>.  It&#8217;s enough to make one wonder why anyone would bother signing up for a Google Maps API key the proper way, when the entire thing can be subverted so easily.</p>
]]></content:encoded>
			<wfw:commentRss>https://codethink.no-ip.org/archives/472/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>[JavaScript] setTimeout() and Closures</title>
		<link>https://codethink.no-ip.org/archives/407</link>
		<comments>https://codethink.no-ip.org/archives/407#comments</comments>
		<pubDate>Sun, 20 Feb 2011 03:46:38 +0000</pubDate>
		<dc:creator><![CDATA[aroth]]></dc:creator>
				<category><![CDATA[coding]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://codethink.no-ip.org/wordpress/?p=407</guid>
		<description><![CDATA[If you&#8217;ve done any amount of non-trivial JavaScript coding then you have probably come across the &#8216;setTimeout()&#8216; function before. In case you haven&#8217;t, this function takes a JavaScript expression and evaluates/executes it after a set delay (specified in milliseconds). For &#8230; <a href="https://codethink.no-ip.org/archives/407">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>If you&#8217;ve done any amount of non-trivial JavaScript coding then you have probably come across the &#8216;<em>setTimeout()</em>&#8216; function before.  In case you haven&#8217;t, this function takes a JavaScript expression and evaluates/executes it after a set delay (specified in milliseconds).  For instance:</p>
<pre class="brush: jscript; title: ; notranslate">setTimeout(&quot;alert('test')&quot;, 5000);</pre>
<p>&#8230;will display an alert box containing the text &#8220;test&#8221; after a 5-second delay.  Simple enough.  But what you may not know is that &#8216;<em>setTimeout()</em>&#8216; also supports an alternate and much more useful usage mode where instead of literal javascript text you can pass a function reference/closure and a variable number of parameters, like so:</p>
<pre class="brush: jscript; title: ; notranslate">setTimeout(alert, 5000, &quot;test&quot;);</pre>
<p>This will produce the same results as the first call, but the syntax is much more readable and much less prone to errors when coding.  Why this variant is barely even mentioned in the <a href="http://www.w3schools.com/js/js_timing.asp" target="_blank">documentation</a> I cannot say, but anyone who has worked with Flash/ActionScript is <a href="http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/utils/package.html#setTimeout()" target="_blank">probably familiar</a> with this syntax. </p>
<p>There is one major limitation to this approach, however; it does not work correctly in Internet Explorer.  That&#8217;s a pretty serious drawback, considering Internet Explorer&#8217;s market share.  But we can fix it by overriding the default &#8216;<em>setTimeout()</em>&#8216; implementation as follows:</p>
<pre class="brush: jscript; title: ; notranslate">window._oldSetTimeout = window.setTimeout;
window.setTimeout = function(closureOrText, delay) {
    if (arguments.length &lt;= 2 || typeof closureOrText != &quot;function&quot;) {
        _oldSetTimeout(closureOrText, delay);
    }
    else {
        var funcArgs = new Array(); 
        for (var index = 2; index &lt; arguments.length; index++) {
            funcArgs.push(arguments[index]);
        }
        _oldSetTimeout(_timeoutCallback(closureOrText, funcArgs), delay);
    }
};
window._timeoutCallback = function(closure, argArray) {
    return function() {
        closure.apply(this, argArray);
    };
};</pre>
<p>Now the behavior will be consistent between Internet Explorer and other browsers.  Note that although the default implementation only needs to be overridden in Internet Explorer, the above code will work correctly in other browsers as well.  Also note that there is one more caveat to be aware of here as well.  In Internet Explorer, functions provided by the system (such as &#8216;<em>alert()</em>&#8216;, &#8216;<em>escape()</em>&#8216;, &#8216;<em>parseInt()</em>&#8216;, etc.) are of a different type than user-defined functions.  Now this wouldn&#8217;t be a huge problem, except that whatever type Internet Explorer uses for its system functions does not support the &#8216;<em>apply()</em>&#8216; method (thanks, Microsoft).  </p>
<p>So even with the above code, if you use &#8216;<em>setTimeout()</em>&#8216; with a system function in Internet Explorer, you will still get incorrect behavior.  We can fix this by revising the code as follows:</p>
<pre class="brush: jscript; title: ; notranslate">window._oldSetTimeout = window.setTimeout;
window.setTimeout = function(closureOrText, delay) {
    var funcArgs = new Array(); 
    for (var index = 2; index &lt; arguments.length; index++) {
        funcArgs.push(arguments[index]);
    }
    if (arguments.length &lt;= 2 || typeof closureOrText != &quot;function&quot;) {
        if (arguments.length &lt;= 2 || typeof closureOrText == &quot;string&quot;) {
            _oldSetTimeout(closureOrText, delay);
        }
        else {
            //hack for IE system functions
            _oldSetTimeout(_timeoutCallbackForSystemFunction (closureOrText, funcArgs), delay);
        }
    }
    else {
        _oldSetTimeout(_timeoutCallback(closureOrText, funcArgs), delay);
    }
};
window._timeoutCallback = function(closure, argArray) {
    return function() {
        closure.apply(this, argArray);
    };
};
window._timeoutCallbackForSystemFunction = function(closure, argArray) {
    return function() {
        if (argArray.length == 1) {
            closure(argArray[0]);
        }
        else if (argArray.length == 2) {
            closure(argArray[0], argArray[1]);
        }
        else {
            alert(&quot;WARN:  Too many arguments passed to system function; timeout callback not executed!&quot;);
        }
    };
};</pre>
<p>This code will produce the correct behavior in Internet Explorer, and is still compatible with all other major browsers.  In Internet Explorer it is limited to supporting system functions with a maximum of 2 parameters, but I&#8217;m not aware of any that require more than that anyways.  An alternate workaround is to define your own function that wraps the system function, and then use the wrapper function in the &#8216;<em>setTimeout()</em>&#8216; call, like so:</p>
<pre class="brush: jscript; title: ; notranslate">var myAlert = function(text) {
    alert(text);
};
setTimeout(myAlert, &quot;5000&quot;, &quot;test&quot;);</pre>
<p>It&#8217;s a bit less convenient to do it this way if you will be working with several different system functions, but this approach will also yield correct behavior in Internet Explorer (and is compatible with other browsers as well).  </p>
<p>In any case, either approach can be used to get the closure-based &#8216;<em>setTimeout()</em>&#8216; syntax working consistently across all major browsers.  And once you have that, there is very little reason to ever prefer the text-based version.  </p>
]]></content:encoded>
			<wfw:commentRss>https://codethink.no-ip.org/archives/407/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>[JavaScript] parseInt() Quirks</title>
		<link>https://codethink.no-ip.org/archives/394</link>
		<comments>https://codethink.no-ip.org/archives/394#comments</comments>
		<pubDate>Sat, 19 Feb 2011 00:13:54 +0000</pubDate>
		<dc:creator><![CDATA[aroth]]></dc:creator>
				<category><![CDATA[coding]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://codethink.no-ip.org/wordpress/?p=394</guid>
		<description><![CDATA[Here&#8217;s a subtle little feature of JavaScript&#8217;s &#8216;parseInt()&#8216; function that I recently stumbled across. The radix used in the parse will default to 8 (octal) if the string you are parsing includes a leading zero. For instance: &#8230;will return 7, &#8230; <a href="https://codethink.no-ip.org/archives/394">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Here&#8217;s a subtle little feature of JavaScript&#8217;s &#8216;<em>parseInt()</em>&#8216; function that I recently stumbled across.  The radix used in the parse will default to 8 (octal) if the string you are parsing includes a leading zero.  For instance:</p>
<pre class="brush: jscript; title: ; notranslate">parseInt(&quot;07&quot;);</pre>
<p>&#8230;will return 7, as expected, but:</p>
<pre class="brush: jscript; title: ; notranslate">parseInt(&quot;08&quot;);</pre>
<p>&#8230;will return 0, because 8 is not a valid digit in a base-8 number system.  Technically the &#8216;<em>parseInt()</em>&#8216; function is behaving to spec in each instance, but this can lead to some very confusing errors if you&#8217;re not expecting this behavior.  A simple fix exists, however:</p>
<pre class="brush: jscript; title: ; notranslate">parseInt(&quot;08&quot;, 10);</pre>
<p>&#8230;will return 8, as expected.  Explicitly specifying a radix of 10 overrides the function&#8217;s quirky default behavior (which as near as I can tell is a relic carried over from C and Java, which both use a leading zero to specify octal literals&#8230;why they didn&#8217;t opt for something more clear, like suffixing the value with &#8216;o&#8217;, I cannot say).  Here is a <a href="http://codethink.no-ip.org/parseInt-test.html" target="_blank">quick example</a> comparing the two.  </p>
<p>An alternate fix to this issue is to simply override the parseInt() function, like so:</p>
<pre class="brush: jscript; title: ; notranslate">			window._oldParseInt = window.parseInt;
			window.parseInt = function(str, rad) {
				if (! rad) {
					return _oldParseInt(str, 10);
				}
				return _oldParseInt(str, rad);
			};</pre>
<p>This will change the behavior of &#8216;<em>parseInt()</em>&#8216; to match that of Java&#8217;s &#8216;<em>Integer.parseInt()</em>&#8216; function (the radix used is always 10 unless the developer explicitly overrides it), which provides for a much more consistent and predictable experience.</p>
<p>Note, however, that this quirky behavior is a <a href="http://www.w3schools.com/jsref/jsref_parseInt.asp" target="_blank">documented</a> (albeit deprecated) feature of the &#8216;<em>parseInt()</em>&#8216; function; though it is certainly not something that one intuitively expects.  Interestingly enough, its deprecation means that browser implementors are free to drop support for this confusing default at any time.  However, complete removal of this feature seems unlikely to happen, as doing so would break existing websites that rely upon it.  </p>
<p>Perhaps a reasonable middle ground would be to preserve the default behavior when the string being parsed includes only valid base-8 numbers, and default to base-10 if any other numbers are present in the string.  That would help in simple cases like the ones shown above, but still may generate confusing output for inputs like &#8220;0107&#8221; and the like.</p>
<p>Really the problem here is one of a poorly designed spec.  Instead of picking the most common usage mode and making that the default, like Java does in its &#8216;<em>Integer.parseInt()</em>&#8216; function, someone decided to try to infer the desired usage mode based upon the input parameter.  And that may be fine when there are no ambiguous mappings from input parameters to usage modes, but that is not the case here.  Whenever such ambiguous mappings exist, it is always better to just make the most common usage mode the default, and let the developer override it if they want something different.</p>
<p>Otherwise you produce code that can yield confusing and unexpected behavior, and you dig everyone else into a hole where they must continue both supporting and working around your poor design decision.</p>
]]></content:encoded>
			<wfw:commentRss>https://codethink.no-ip.org/archives/394/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
