<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Duncan's blog</title>
	<atom:link href="http://duncan99.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://duncan99.wordpress.com</link>
	<description>Just another WordPress.com weblog</description>
	<lastBuildDate>Mon, 20 May 2013 08:53:38 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='duncan99.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Duncan's blog</title>
		<link>http://duncan99.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://duncan99.wordpress.com/osd.xml" title="Duncan&#039;s blog" />
	<atom:link rel='hub' href='http://duncan99.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Try, Catch&#8230; Ignore!</title>
		<link>http://duncan99.wordpress.com/2013/05/20/try-catch-ignore/</link>
		<comments>http://duncan99.wordpress.com/2013/05/20/try-catch-ignore/#comments</comments>
		<pubDate>Mon, 20 May 2013 08:53:37 +0000</pubDate>
		<dc:creator>duncan</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[douglas crockford]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jslint]]></category>
		<category><![CDATA[try catch]]></category>

		<guid isPermaLink="false">http://duncan99.wordpress.com/?p=1677</guid>
		<description><![CDATA[I was using JSLint today before committing in a javascript file. It was doing some presentational effects we didn&#8217;t expect to work in all browsers, so there was a try-catch wrapped around it. And the catch block was empty. Something a bit like this in fact: try { ... } catch (exception) { //browser does [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=duncan99.wordpress.com&#038;blog=4274552&#038;post=1677&#038;subd=duncan99&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>I was using <a href="http://www.jslint.com/" title="JSLint">JSLint</a> today before committing in a javascript file.  It was doing some presentational effects we didn&#8217;t expect to work in all browsers, so there was a try-catch wrapped around it.  And the catch block was empty.</p>
<p>Something a bit like this in fact:</p>
<pre style="font-size:larger;">	try {
		...			
	} catch (exception) {
		//browser does not support doing this, so catch error and continue
	}</pre>
<p>JSLint gave me this error message:<br />
<em>Expected &#8216;ignore&#8217; and instead saw &#8216;exception&#8217;.</em></p>
<p>A <a href="http://stackoverflow.com/a/16626793/492335">very useful answer</a> on StackOverflow explains what this is about.  Douglas Crockford has decided that if you have an empty catch block, your variable should be called &#8216;ignore&#8217;, to make it clearer you&#8217;re doing this deliberately and haven&#8217;t just forgot to do something with the exception.  </p>
<p>So this code works:</p>
<pre style="font-size:larger;">	try {
		...			
	} catch (ignore) {
		//browser does not support doing this, so catch error and continue
	}</pre>
<p>And conversely it only works if you don&#8217;t do anything in that block.  i.e. this code errors (with &#8220;<em>Unexpected &#8216;ignore&#8217;</em>&#8220;):</p>
<pre style="font-size:larger;">	try {
		...			
	} catch (ignore) {
		alert('there was an error');
	}</pre>
<p>Personally I think this is a great idea, it makes the code much more obvious.  I&#8217;m going to start doing this in other languages too.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/duncan99.wordpress.com/1677/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/duncan99.wordpress.com/1677/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=duncan99.wordpress.com&#038;blog=4274552&#038;post=1677&#038;subd=duncan99&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://duncan99.wordpress.com/2013/05/20/try-catch-ignore/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/e5594b71e9f54f3e73f6294b054f5616?s=96&#38;d=http%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">duncan</media:title>
		</media:content>
	</item>
		<item>
		<title>Google Maps API – draggable polylines</title>
		<link>http://duncan99.wordpress.com/2013/03/01/google-maps-api-draggable-polylines/</link>
		<comments>http://duncan99.wordpress.com/2013/03/01/google-maps-api-draggable-polylines/#comments</comments>
		<pubDate>Fri, 01 Mar 2013 18:26:02 +0000</pubDate>
		<dc:creator>duncan</dc:creator>
				<category><![CDATA[Google Maps]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[google maps]]></category>
		<category><![CDATA[google maps api]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[map]]></category>

		<guid isPermaLink="false">http://duncan99.wordpress.com/?p=1661</guid>
		<description><![CDATA[Update: a lot of the javascript in this article was based on old code I wrote a while ago&#8230; thinking about it after I initially published the article I decided to rewrite it slightly. So previously I had one array for destinations, and three global arrays for labels, polylines and markers. It&#8217;s much simpler in [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=duncan99.wordpress.com&#038;blog=4274552&#038;post=1661&#038;subd=duncan99&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><strong>Update:</strong> a lot of the javascript in this article was based on old code I wrote a while ago&#8230; thinking about it after I initially published the article I decided to rewrite it slightly. So previously I had one array for destinations, and three global arrays for labels, polylines and markers. It&#8217;s much simpler in this case just to have one global array which contains destinations, labels, polylines and markers.</p>
<p>So my previous post in this series added <a title="Google Maps API – polylines and events" href="http://duncan99.wordpress.com/2013/02/28/google-maps-api-polylines-and-events/">event listeners to polylines</a>, this time I want to make the lines draggable.  In this case I want to have one marker I can move around the map, and the polylines connecting it to the other markers will update to stay elastically-attached to the one draggable marker.  And the distances will update automatically.  Again we&#8217;re using the Label code courtesy of <a href="http://blog.mridey.com/">Marc Ridey</a> (which I&#8217;m not going to repeat here, see my earlier blogpost).  And the rest of the code remains quite similar to previously, with some key differences.</p>
<pre style="font-size:larger;">	
var arrDestinations;

function initialize() {
	var map, i, j, latLng, stuDistances, inBetween, labelMarker;

	arrDestinations = [
		{title: 'Place A',	lat: 34.602694,	lng: -106.066132},
		{title: 'Place B',	lat: 33.917153,	lng: -106.869736},
		{title: 'Place C',	lat: 34.254946,	lng: -105.599442}
	];

	var stuHome = {title: 'Where I am', lat: 34.148181, lng: -106.17897};

	var homeLatlng = new google.maps.LatLng(stuHome.lat, stuHome.lng);
	var myOptions = {
		zoom: 9,
		center: homeLatlng,
		mapTypeId: google.maps.MapTypeId.SATELLITE
	};
	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

	var homeMarker = new google.maps.Marker({
		position: homeLatlng, 
		map: map, 
		title: stuHome.title,
		draggable: true
	});

	$('#tableNeighbours').append(
		  '&lt;tr&gt;'
		+ '&lt;th&gt;Destination&lt;/th&gt;'
		+ '&lt;th colspan="2"&gt;' + stuHome.title + '&lt;/th&gt;'
		+ '&lt;/tr&gt;'
	);

	for (i = 0; i &lt; arrDestinations.length; i++) {
		latLng = new google.maps.LatLng(arrDestinations[i].lat, arrDestinations[i].lng);

		arrDestinations[i].marker = new google.maps.Marker({
			position: latLng,
			map: map, 
			title: arrDestinations[i].title,
			icon: &#039;http://maps.google.co.uk/intl/en_ALL/mapfiles/ms/micons/green-dot.png&#039;
		});

		// draw lines between each marker and home.  these are curved lines, not as the crow flies, i.e. they take into account the curvature of the earth (only noticable on longer distances)
		arrDestinations[i].polyline = new google.maps.Polyline({
			path: [homeLatlng, latLng],
			strokeColor: &quot;#FF0000&quot;,
			strokeOpacity: 0.5,
			strokeWeight: 4,
			geodesic: true,
			map: map
		});


		// calculate the distance between home and this marker
		stuDistances = calculateDistances(homeLatlng, latLng);
		$(&#039;#tableNeighbours&#039;).append(
			  &#039;&lt;tr id=&quot;row&#039; + i + &#039;&quot;&gt;&#039; 
			+ &#039;&lt;td&gt;&#039; + arrDestinations[i].title + &#039;&lt;/td&gt;&#039;
			+ &#039;&lt;td class=&quot;km&quot;&gt;&#039; + stuDistances.km + &#039; km&lt;/td&gt;&#039;
			+ &#039;&lt;td class=&quot;miles&quot;&gt;&#039; + stuDistances.miles + &#039; miles&lt;/td&gt;&#039;
			+ &#039;&lt;/tr&gt;&#039;
		);

		// get the point half-way between this marker and the home marker
		inBetween = google.maps.geometry.spherical.interpolate(homeLatlng, latLng, 0.5);  

		// create an invisible marker
		labelMarker = new google.maps.Marker({  
			position: inBetween,  
			map: map,
			visible: false
		});

		arrDestinations[i].label = new Label();

		arrDestinations[i].label.bindTo(&#039;position&#039;, labelMarker, &#039;position&#039;);
		arrDestinations[i].label.set(&#039;text&#039;, stuDistances.miles + &#039; miles&#039;);
		arrDestinations[i].label.setMap(map);
	}

	// lets make the home marker draggable, but none of the others, just for illustrating how we can make the polylines move dynamically
	google.maps.event.addListener(homeMarker, &#039;dragend&#039;, function() {
		var i, stuDistance, inBetween, marker, markerLatLng;
		var homeLatLng = homeMarker.getPosition();

		// do this for each of the markers 
		for (i = 0; i &lt; arrDestinations.length; i++) {
			markerLatLng = arrDestinations[i].marker.getPosition();

			arrDestinations[i].polyline.setPath([homeLatLng, markerLatLng]);
			stuDistance = calculateDistances(homeLatLng, markerLatLng);
			arrDestinations[i].label.set(&#039;text&#039;, stuDistance.miles + &#039; miles&#039;);

			// update the position of the marker which the label is bound to
			inBetween = google.maps.geometry.spherical.interpolate(homeLatLng, markerLatLng, 0.5);
			marker = new google.maps.Marker({  
				position: inBetween,  
				map: map,
				visible: false
			});
			arrDestinations[i].label.set(&#039;position&#039;, inBetween);

			// update values in table
			$(&#039;#row&#039; + i + &#039; td.km&#039;).text(stuDistance.km + &#039; kilometres&#039;);
			$(&#039;#row&#039; + i + &#039; td.miles&#039;).text(stuDistance.miles + &#039; miles&#039;);
		}
	});
}

function calculateDistances(start,end) {
	var stuDistances = {};

	stuDistances.metres = google.maps.geometry.spherical.computeDistanceBetween(start, end);	// distance in metres rounded to 1dp
	stuDistances.km = Math.round(stuDistances.metres / 1000 *10)/10;				// distance in km rounded to 1dp
	stuDistances.miles = Math.round(stuDistances.metres / 1000 * 0.6214 *10)/10;			// distance in miles rounded to 1dp

	return stuDistances;
}

google.maps.event.addDomListener(window, &#039;load&#039;, initialize);</pre>
<p>This time when creating the &#8216;homeMarker&#8217; I make it draggable using this option: <code style="font-size:larger;">draggable: true</code>.</p>
<p>I also added a class to each of the kilometres and miles cells, so they&#8217;re easy to identify later when I want to dynamically update them.</p>
<p>And the markers are appended into an array so we can use them later when dragging the centre marker.</p>
<p>And this time we make the labels appear automatically by calling <code style="font-size:larger;">label.setMap(map);</code> as we create each marker, and I never remove them.</p>
<p>We then have a new event listener for the &#8216;<em>dragend</em>&#8216; event on the homeMarker.  I&#8217;ve tried using &#8216;<em>drag</em>&#8216; instead, but it seemed slightly processor-intensive to use (although it did automatically redraw lines and distances as I dragged  &#8211; now I&#8217;m just redrawing them when the user releases the marker).</p>
<p>And this is what I see. Dragging the red marker redraws the polylines and updates the distances on the labels:<br />
<a href="http://duncan99.files.wordpress.com/2013/03/new-mexico.png"><img class="aligncenter size-full wp-image-1667" alt="new mexico" src="http://duncan99.files.wordpress.com/2013/03/new-mexico.png?w=599&#038;h=599" width="599" height="599" /></a></p>
<p>…and the table underneath displays the distances in miles and km, and automatically updates along with the labels:</p>
<table id="tableNeighbours" border="1">
<tbody>
<tr>
<th>Destination</th>
<th colspan="2">Where I am</th>
</tr>
<tr id="row0">
<td>Place A</td>
<td class="km">51.6 km</td>
<td class="miles">32.1 miles</td>
</tr>
<tr id="row1">
<td>Place B</td>
<td class="km">68.7 km</td>
<td class="miles">42.7 miles</td>
</tr>
<tr id="row2">
<td>Place C</td>
<td class="km">54.7 km</td>
<td class="miles">34 miles</td>
</tr>
</tbody>
</table>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/duncan99.wordpress.com/1661/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/duncan99.wordpress.com/1661/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=duncan99.wordpress.com&#038;blog=4274552&#038;post=1661&#038;subd=duncan99&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://duncan99.wordpress.com/2013/03/01/google-maps-api-draggable-polylines/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/e5594b71e9f54f3e73f6294b054f5616?s=96&#38;d=http%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">duncan</media:title>
		</media:content>

		<media:content url="http://duncan99.files.wordpress.com/2013/03/new-mexico.png" medium="image">
			<media:title type="html">new mexico</media:title>
		</media:content>
	</item>
		<item>
		<title>Adobe ColdFusion Developer Center</title>
		<link>http://duncan99.wordpress.com/2013/03/01/adobe-coldfusion-developer-center/</link>
		<comments>http://duncan99.wordpress.com/2013/03/01/adobe-coldfusion-developer-center/#comments</comments>
		<pubDate>Fri, 01 Mar 2013 10:40:32 +0000</pubDate>
		<dc:creator>duncan</dc:creator>
				<category><![CDATA[Coldfusion]]></category>
		<category><![CDATA[adobe coldfusion]]></category>
		<category><![CDATA[cfmap]]></category>

		<guid isPermaLink="false">http://duncan99.wordpress.com/?p=1654</guid>
		<description><![CDATA[I&#8217;d heard there was a hotfix change to Adobe ColdFusion 9 &#38; 10 for the CFMap tag, to start using Google Maps API v3 instead of the deprecated (and very-soon to be unavailable) Google Maps API v2. So I decided to make an infrequent visit to the Developer Center and see if I could find [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=duncan99.wordpress.com&#038;blog=4274552&#038;post=1654&#038;subd=duncan99&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>I&#8217;d heard there was a <a href="http://blogs.coldfusion.com/post.cfm/new-updates-for-coldfusion-9-9-0-1-9-0-2-and-10-java-7-now-supported">hotfix change to Adobe ColdFusion 9 &amp; 10</a> for the CFMap tag, to start using Google Maps API v3 instead of the deprecated (and very-soon to be unavailable) Google Maps API v2. So I decided to make an infrequent visit to the <a href="http://www.adobe.com/devnet/coldfusion.html">Developer Center</a> and see if I could find anything about it. Nothing obvious, but I noticed this:</p>
<p><a href="http://duncan99.files.wordpress.com/2013/03/cfdev-center.png"><img class="aligncenter size-full wp-image-1657" alt="CFDev Center" src="http://duncan99.files.wordpress.com/2013/03/cfdev-center.png?w=358&#038;h=352" width="358" height="352" /></a></p>
<p>Aha, a useful example on &#8216;working with Google maps&#8217; using cfmap!  Unfortunately<a href="http://cfsnippets.coldfusionportal.org/demos/ui/cfmap/basic.cfm"> that link</a> just displays a map. It doesn&#8217;t show any code, so is useless as an example of using CFMap.  Similarly the other link on <a href="http://cfsnippets.coldfusionportal.org/demos/office/cfspreadsheet/read.cfm">using cfspreadsheet</a> merely shows me a dumped query and a table&#8230; very useful I&#8217;m sure.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/duncan99.wordpress.com/1654/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/duncan99.wordpress.com/1654/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=duncan99.wordpress.com&#038;blog=4274552&#038;post=1654&#038;subd=duncan99&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://duncan99.wordpress.com/2013/03/01/adobe-coldfusion-developer-center/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/e5594b71e9f54f3e73f6294b054f5616?s=96&#38;d=http%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">duncan</media:title>
		</media:content>

		<media:content url="http://duncan99.files.wordpress.com/2013/03/cfdev-center.png" medium="image">
			<media:title type="html">CFDev Center</media:title>
		</media:content>
	</item>
		<item>
		<title>Google Maps API – polylines and events</title>
		<link>http://duncan99.wordpress.com/2013/02/28/google-maps-api-polylines-and-events/</link>
		<comments>http://duncan99.wordpress.com/2013/02/28/google-maps-api-polylines-and-events/#comments</comments>
		<pubDate>Thu, 28 Feb 2013 18:00:29 +0000</pubDate>
		<dc:creator>duncan</dc:creator>
				<category><![CDATA[Google Maps]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[event listeners]]></category>
		<category><![CDATA[google map labels]]></category>
		<category><![CDATA[google map polylines]]></category>
		<category><![CDATA[google maps]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jquery]]></category>

		<guid isPermaLink="false">http://duncan99.wordpress.com/?p=1643</guid>
		<description><![CDATA[Update: a lot of the javascript in this article was based on old code I wrote a while ago… thinking about it after I initially published the article I decided to rewrite it slightly. So previously I had one array for destinations, and two global arrays for labels and polylines. It’s much simpler in this [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=duncan99.wordpress.com&#038;blog=4274552&#038;post=1643&#038;subd=duncan99&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><strong>Update:</strong> a lot of the javascript in this article was based on old code I wrote a while ago… thinking about it after I initially published the article I decided to rewrite it slightly. So previously I had one array for destinations, and two global arrays for labels and polylines. It’s much simpler in this case just to have one global array which contains destinations, labels and polylines.</p>
<p>So following on from the previous post, <a title="Permalink to Google Maps API – polylines and distances" href="https://duncan99.wordpress.com/2013/02/14/google-maps-api-polylines-and-distances/" rel="bookmark">Google Maps API – polylines and distances</a>, let&#8217;s try enhancing that code a bit.</p>
<p>Firstly, as well as having a table showing distances, I want to show a label on each polyline with the distance in miles.  For that we can create a <a href="https://developers.google.com/maps/documentation/javascript/overlays#CustomOverlays">custom overlay</a> by prototyping the <code style="font-size:larger;">OverlayView</code> class.</p>
<p>Secondly, let&#8217;s have some events associated with the map &#8211; when I click on a polyline I want to see that label.  Also we can have an event listener on the table of distances which triggers the same event on the polylines.</p>
<p>Here&#8217;s what I see when I click on a polyline, or mouseover the table row that contains its data.</p>
<p><a href="http://duncan99.files.wordpress.com/2013/02/map-label.png"><img class="aligncenter size-full wp-image-1648" alt="map label" src="http://duncan99.files.wordpress.com/2013/02/map-label.png?w=287&#038;h=346" width="287" height="346" /></a></p>
<p>So, here&#8217;s the Label class &#8211; this code is almost entirely from a <a href="http://blog.mridey.com/2009/09/label-overlay-example-for-google-maps.html">blogpost by Marc Ridey</a> with one tiny change on my part.  Custom Overlays need to prototype <code style="font-size:larger;">google.maps.OverlayView()</code>.  It then must define <code style="font-size:larger;">onAdd()</code>, <code style="font-size:larger;">onRemove()</code> and <code style="font-size:larger;">draw()</code> functions.  The only thing I changed here from Marc&#8217;s original version was to use <code style="font-size:larger;">var pane = this.getPanes().floatPane;</code> instead of <code style="font-size:larger;">var pane = this.getPanes().overlayLayer;</code>  The OverlayLayer meant the labels appeared underneath polylines and markers.  The floatPane is the equivalent of using a higher z-index, so the labels now float above those items.</p>
<pre style="font-size:larger;">
// Define the overlay, derived from google.maps.OverlayView
function Label(opt_options) {
	// Initialization
	this.setValues(opt_options);
	
	// Label specific
	var span = this.span_ = document.createElement('span');
	span.style.cssText = 'position: relative; left: -50%; top: -8px; ' +
	                     'white-space: nowrap; border: 1px solid blue; ' +
	                     'padding: 2px; background-color: white';
	
	var div = this.div_ = document.createElement('div');
	div.appendChild(span);
	div.style.cssText = 'position: absolute; display: none';
}
Label.prototype = new google.maps.OverlayView();

// Implement onAdd
Label.prototype.onAdd = function() {
	var pane = this.getPanes().floatPane;
	pane.appendChild(this.div_);
	
	// Ensures the label is redrawn if the text or position is changed.
	var me = this;
	this.listeners_ = [
		google.maps.event.addListener(this, 'position_changed',
			function() { me.draw(); }),
		google.maps.event.addListener(this, 'text_changed',
			function() { me.draw(); })
	];
};

// Implement onRemove
Label.prototype.onRemove = function() {
	var i, I;
	this.div_.parentNode.removeChild(this.div_);
	
	// Label is removed from the map, stop updating its position/text.
	for (i = 0, I = this.listeners_.length; i &lt; I; ++i) {
		google.maps.event.removeListener(this.listeners_[i]);
	}
};

// Implement draw
Label.prototype.draw = function() {
	var projection = this.getProjection();
	var position = projection.fromLatLngToDivPixel(this.get(&#039;position&#039;));
	
	var div = this.div_;
	div.style.left = position.x + &#039;px&#039;;
	div.style.top = position.y + &#039;px&#039;;
	div.style.display = &#039;block&#039;;
	
	this.span_.innerHTML = this.get(&#039;text&#039;).toString();
};</pre>
<p>And so then here&#8217;s the rest of the javascript:</p>
<pre style="font-size:larger;">
var arrDestinations;

function initialize() {
	var map, i, j, latLng, stuDistances, inBetween, labelMarker;

	arrDestinations = [
		{title: 'Keswick',		lat: 54.60039,		lng: -3.13632},
		{title: 'Coniston',		lat: 54.36897,		lng: -3.07561},
		{title: 'Lake District',	lat: 54.5003526,	lng: -3.0844116},
		{title: 'Cumbria',		lat: 54.57723,		lng: -2.79748}
	];
	
	var stuHome = {title: 'Ambleside', lat: 54.42838, lng: -2.9623};
	
	var homeLatlng = new google.maps.LatLng(stuHome.lat, stuHome.lng);
	var myOptions = {
		zoom: 10,
		center: homeLatlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
			
	var homeMarker = new google.maps.Marker({
		position: homeLatlng, 
		map: map, 
		title: stuHome.title
	});
	
	$('#tableNeighbours').append(
		  '&lt;tr&gt;'
		+ '&lt;th&gt;Destination&lt;/th&gt;'
		+ '&lt;th colspan="2"&gt;' + stuHome.title + '&lt;/th&gt;'
		+ '&lt;/tr&gt;'
	);
			  
	for (i = 0; i &lt; arrDestinations.length; i++) {
		latLng = new google.maps.LatLng(arrDestinations[i].lat, arrDestinations[i].lng);
		
		arrDestinations[i].marker = new google.maps.Marker({
			position: latLng,
			map: map, 
			title: arrDestinations[i].title,
			icon: &#039;http://maps.google.co.uk/intl/en_ALL/mapfiles/ms/micons/green-dot.png&#039;
		});
					
		// draw lines between each marker and home.  these are curved lines, not as the crow flies, i.e. they take into account the curvature of the earth (only noticable on longer distances)
		arrDestinations[i].polyline = new google.maps.Polyline({
			path: [homeLatlng, latLng],
			strokeColor: &quot;#FF0000&quot;,
			strokeOpacity: 0.5,
			strokeWeight: 4,
			geodesic: true,
			map: map,
			polylineID: i
		});
					
		// calculate the distance between home and this marker
		stuDistances = calculateDistances(homeLatlng, latLng);
		$(&#039;#tableNeighbours&#039;).append(
			  &#039;&lt;tr id=&quot;row&#039; + i + &#039;&quot;&gt;&#039; 
			+ &#039;&lt;td&gt;&#039; + arrDestinations[i].title + &#039;&lt;/td&gt;&#039;
			+ &#039;&lt;td&gt;&#039; + stuDistances.km + &#039; km&lt;/td&gt;&#039;
			+ &#039;&lt;td&gt;&#039; + stuDistances.miles + &#039; miles&lt;/td&gt;&#039;
			+ &#039;&lt;/tr&gt;&#039;
		);
		
		// get the point half-way between this marker and the home marker
		inBetween = google.maps.geometry.spherical.interpolate(homeLatlng, latLng, 0.5);  
		
		// create an invisible marker
		labelMarker = new google.maps.Marker({  
			position: inBetween,  
			map: map,
			visible: false
		});
		
		arrDestinations[i].label = new Label();
		
		arrDestinations[i].label.bindTo(&#039;position&#039;, labelMarker, &#039;position&#039;);
		arrDestinations[i].label.set(&#039;text&#039;, stuDistances.miles + &#039; miles&#039;);
		
		// we&#039;ll use this ID later:
		arrDestinations[i].label.polylineID = i;
	
		// lets add an event listener, if you click the line, i&#039;ll tell you the distance
		google.maps.event.addListener(arrDestinations[i].polyline, &#039;click&#039;, function() {
			// remove other labels
			for (j = 0; j &lt; arrDestinations.length; j++){
				if (this.polylineID != j) {
					if(typeof(arrDestinations[j].label) != &quot;undefined&quot;){
						arrDestinations[j].label.setMap(null);
					}
				} else {
					arrDestinations[j].label.setMap(map);
				}
			}
		});
	}
}

function calculateDistances(start,end) {
	var stuDistances = {};
	
	stuDistances.metres = google.maps.geometry.spherical.computeDistanceBetween(start, end);	// distance in metres rounded to 1dp
	stuDistances.km = Math.round(stuDistances.metres / 1000 *10)/10;							// distance in km rounded to 1dp
	stuDistances.miles = Math.round(stuDistances.metres / 1000 * 0.6214 *10)/10;				// distance in miles rounded to 1dp

	return stuDistances;
}

function removeAllLabels() {
	var i;
	// remove other markers
	for (i = 0; i &lt; arrDestinations.length; i++){
		// don&#039;t remove the current label
		if(typeof(arrDestinations[i].label) != &quot;undefined&quot;){
			arrDestinations[i].label.setMap(null);
		}
	}
}

$(document).ready(function() {
	$(&#039;table&#039;).delegate(&quot;td&quot;, &quot;mouseover mouseout&quot;, function(e) {
		if (e.type == &#039;mouseover&#039;) {
			var id = $(this).parent().attr(&#039;id&#039;).replace(&#039;row&#039;, &#039;&#039;);
			google.maps.event.trigger(arrDestinations[id].polyline, &#039;click&#039;);
		} else {
			removeAllLabels();
		}
	});
});

google.maps.event.addDomListener(window, &#039;load&#039;, initialize);</pre>
<p>Some other changes worth mentioning from the previous article. We&#8217;re using <code style="font-size:larger;">google.maps.geometry.spherical.interpolate</code> to calculate a point 50% of the way along the polyline. This could also be used if you wanted to place markers at regular intervals along the line for instance.</p>
<p>We then create an invisible marker at that position, and bind our Label to it.  And we add all the labels into an array.</p>
<p>Then we have an event listener on the polyline for any &#8216;click&#8217; events.  When someone clicks on a line, I want to hide all the other labels and only show this one.  Alternatively you might want to not have any event listener, and just show all the labels all the time.</p>
<p>Then there&#8217;s another event listener for when we mouseover / mouseout any table cells.  Because we&#8217;re adding the table rows dynamically via the JS, I&#8217;m using the jQuery .delegate() function.  Whenever you mouseout from a  TD, the marker is removed.  If you mouseover, we can simply trigger a click on that polyline, which will then execute the google maps event listener.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/duncan99.wordpress.com/1643/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/duncan99.wordpress.com/1643/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=duncan99.wordpress.com&#038;blog=4274552&#038;post=1643&#038;subd=duncan99&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://duncan99.wordpress.com/2013/02/28/google-maps-api-polylines-and-events/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/e5594b71e9f54f3e73f6294b054f5616?s=96&#38;d=http%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">duncan</media:title>
		</media:content>

		<media:content url="http://duncan99.files.wordpress.com/2013/02/map-label.png" medium="image">
			<media:title type="html">map label</media:title>
		</media:content>
	</item>
		<item>
		<title>Google Maps API &#8211; polylines and distances</title>
		<link>http://duncan99.wordpress.com/2013/02/14/google-maps-api-polylines-and-distances/</link>
		<comments>http://duncan99.wordpress.com/2013/02/14/google-maps-api-polylines-and-distances/#comments</comments>
		<pubDate>Thu, 14 Feb 2013 18:56:57 +0000</pubDate>
		<dc:creator>duncan</dc:creator>
				<category><![CDATA[Google Maps]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[google]]></category>
		<category><![CDATA[google maps]]></category>
		<category><![CDATA[google maps api]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[polylines]]></category>

		<guid isPermaLink="false">http://duncan99.wordpress.com/?p=1630</guid>
		<description><![CDATA[So after a basic introduction to polylines, let&#8217;s try doing a bit more with them. Here&#8217;s a simple example based on something I was doing for work. Supposing you have a bunch of different locations, and you want to show the distance between them? In this case I had one central destination, and I wanted [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=duncan99.wordpress.com&#038;blog=4274552&#038;post=1630&#038;subd=duncan99&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>So after a <a href="http://duncan99.wordpress.com/2013/02/12/google-maps-api-polylines/" title="Google Maps API – polylines">basic introduction to polylines</a>, let&#8217;s try doing a bit more with them. Here&#8217;s a simple example based on something I was doing for work. Supposing you have a bunch of different locations, and you want to show the distance between them? In this case I had one central destination, and I wanted to show the distance from there to several nearby towns. I did this initially using polylines, as in this example, although in reality it would be more useful to show driving directions (more on that in a future post).</p>
<p>Here&#8217;s what I came up with:</p>
<p><a href="http://duncan99.files.wordpress.com/2013/02/ambleside.png"><img class="aligncenter size-full wp-image-1631" alt="ambleside" src="http://duncan99.files.wordpress.com/2013/02/ambleside.png?w=600&#038;h=500" width="600" height="500" /></a></p>
<p>And I displayed this table beneath the map: </p>
<table id="tableNeighbours" border="1">
<tbody>
<tr>
<th>Destination</th>
<th colspan="2">Distance from Ambleside</th>
</tr>
<tr>
<td>Keswick</td>
<td>22.2 km</td>
<td>13.8 miles</td>
</tr>
<tr>
<td>Coniston</td>
<td>9.9 km</td>
<td>6.1 miles</td>
</tr>
<tr>
<td>Lake District</td>
<td>11.3 km</td>
<td>7 miles</td>
</tr>
<tr>
<td>Cumbria</td>
<td>19.7 km</td>
<td>12.2 miles</td>
</tr>
</tbody>
</table>
<p>And here&#8217;s the Javascript I used to do it. Originally I was getting my coordinates from the database using ColdFusion, and then writing them into the Javascript. I was also doing some infowindows attached to the markers, and labels on the polylines indicating the distances. But for this post I&#8217;ve just kept it simple for now.</p>
<pre style="font-size:larger;">&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;lines between the nearest destinations showing distance&lt;/title&gt;

&lt;meta name="viewport" content="initial-scale=1.0, user-scalable=no" /&gt;
&lt;style type="text/css"&gt;
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { width:600px; height:500px }
&lt;/style&gt;
&lt;!-- need to load the geometry library for calculating distances --&gt;
&lt;script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=geometry&amp;sensor=false"&gt;&lt;/script&gt;

&lt;script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js" type="text/javascript"&gt;&lt;/script&gt;

&lt;script type="text/javascript"&gt;
    function initialize() {
        var map, i, latLng, marker, polyline, stuDistances;
    
        var arrDestinations = [
            {title: 'Keswick',        lat: 54.60039,   lng: -3.13632},
            {title: 'Coniston',       lat: 54.36897,   lng: -3.07561},
            {title: 'Lake District',  lat: 54.5003526, lng: -3.0844116},
            {title: 'Cumbria',        lat: 54.57723,   lng: -2.79748}
        ];
        
        var stuHome = {title: 'Ambleside', lat: 54.42838, lng: -2.9623};
        
        var homeLatlng = new google.maps.LatLng(stuHome.lat, stuHome.lng);
        var myOptions = {
            zoom: 10,
            center: homeLatlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
                
        var homeMarker = new google.maps.Marker({
            position: homeLatlng, 
            map: map, 
            title: stuHome.title
        });
        
        $('#tableNeighbours').append(
              '&lt;tr&gt;'
            + '&lt;th&gt;Destination&lt;/th&gt;'
            + '&lt;th colspan="2"&gt;' + stuHome.title + '&lt;/th&gt;'
            + '&lt;/tr&gt;'
        );
                  
        for (i = 0; i &lt; arrDestinations.length; i++) {
            latLng = new google.maps.LatLng(arrDestinations[i].lat, arrDestinations[i].lng);
            marker = new google.maps.Marker({
                position: latLng,
                map: map, 
                title: arrDestinations[i].title,
                icon: 'http://maps.google.co.uk/intl/en_ALL/mapfiles/ms/micons/green-dot.png'
            });
                        
            // draw lines between each marker and home.  these are curved lines, not as the crow flies, i.e. they take into account the curvature of the earth (only noticable on longer distances)
            polyline = new google.maps.Polyline({
                path: [homeLatlng, latLng],
                strokeColor: "#FF0000",
                strokeOpacity: 0.5,
                strokeWeight: 4,
                geodesic: true,
                map: map
            });
            
            // calculate the distance between home and this marker
            stuDistances = calculateDistances(homeLatlng, latLng);
            $('#tableNeighbours').append(
                  '&lt;tr&gt;' 
                + '&lt;td&gt;' + arrDestinations[i].title + '&lt;/td&gt;'
                + '&lt;td&gt;' + stuDistances.km + ' km&lt;/td&gt;'
                + '&lt;td&gt;' + stuDistances.miles + ' miles&lt;/td&gt;'
                + '&lt;/tr&gt;'
            );
        }
    }
    
    function calculateDistances(start,end) {
        var stuDistances = {};
        
        stuDistances.metres = google.maps.geometry.spherical.computeDistanceBetween(start, end);    // distance in metres
        stuDistances.km = Math.round(stuDistances.metres / 1000 *10)/10;                            // distance in km rounded to 1dp
        stuDistances.miles = Math.round(stuDistances.metres / 1000 * 0.6214 *10)/10;                // distance in miles rounded to 1dp
        
        return stuDistances;
    }
    
    google.maps.event.addDomListener(window, 'load', initialize);
&lt;/script&gt;

&lt;/head&gt;
&lt;body&gt;
    &lt;div id="map_canvas"&gt;&lt;/div&gt;
    
    &lt;table id="tableNeighbours" border="1"&gt;&lt;/table&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>So I&#8217;m dynamically adding the distance information from each location to the table as each marker is added.  You&#8217;ll notice that in the calculateDistances function, instead of simply dividing the metres distance by 1000 to get it in kilometres, I multiply by 10, then round, then divide by 10.  This is in order to round the distances to 1 decimal place.</p>
<p>e.g. the distance between my Ambleside and Keswick markers is 22205.96176105692 metres, according to Google.  So to convert that to kilometres if I just divide by 1000 it gives:<br />
22.20596176105692<br />
The Round() function rounds to the nearest integer.  So instead let&#8217;s only divide by 100 (or divide by 1000 then multiply by 10, as I&#8217;m doing, same thing).  Which gives:<br />
222.0596176105692<br />
Then we call Math.round(), which gives:<br />
222<br />
And finally divide that by 10:<br />
22.2<br />
There are other ways to achieve this in javascript of course!</p>
<p>Notice as well that we&#8217;ve added the optional `libraries=geometry` parameter to the URL for the Google Maps JS file.  This is so we can use the <a href="https://developers.google.com/maps/documentation/javascript/geometry">Geometry Library</a> to calculate the distance between locations, using the <strong>computeDistanceBetween</strong> function.  Also read this <a href="http://www.svennerberg.com/2011/04/calculating-distances-and-areas-in-google-maps-api-3/">useful article</a> which explains some more about using the Geometry Library.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/duncan99.wordpress.com/1630/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/duncan99.wordpress.com/1630/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=duncan99.wordpress.com&#038;blog=4274552&#038;post=1630&#038;subd=duncan99&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://duncan99.wordpress.com/2013/02/14/google-maps-api-polylines-and-distances/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/e5594b71e9f54f3e73f6294b054f5616?s=96&#38;d=http%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">duncan</media:title>
		</media:content>

		<media:content url="http://duncan99.files.wordpress.com/2013/02/ambleside.png" medium="image">
			<media:title type="html">ambleside</media:title>
		</media:content>
	</item>
		<item>
		<title>Google Maps API &#8211; polylines</title>
		<link>http://duncan99.wordpress.com/2013/02/12/google-maps-api-polylines/</link>
		<comments>http://duncan99.wordpress.com/2013/02/12/google-maps-api-polylines/#comments</comments>
		<pubDate>Tue, 12 Feb 2013 18:41:40 +0000</pubDate>
		<dc:creator>duncan</dc:creator>
				<category><![CDATA[Google Maps]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[geodesic]]></category>
		<category><![CDATA[google maps]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[maps]]></category>
		<category><![CDATA[polylines]]></category>

		<guid isPermaLink="false">http://duncan99.wordpress.com/?p=1480</guid>
		<description><![CDATA[So now we&#8217;ve created a map, added markers and infowindows. Maybe you want to start drawing lines and shapes on it. Supposing I have two markers, and I just want to draw a line connecting them. &#60;script type="text/javascript"&#62; function initialize() { var homeLatlng = new google.maps.LatLng(51.476706,0); var map = new google.maps.Map(document.getElementById("map"), { zoom: 15, center: [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=duncan99.wordpress.com&#038;blog=4274552&#038;post=1480&#038;subd=duncan99&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>So now we&#8217;ve <a href="http://duncan99.wordpress.com/2011/09/18/google-maps-api-an-introduction/" title="Google Maps API – an introduction">created a map</a>, <a href="http://duncan99.wordpress.com/2011/09/25/google-maps-api-adding-markers/" title="Google Maps API – adding markers">added markers</a> and <a href="http://duncan99.wordpress.com/2011/10/08/google-maps-api-infowindows/" title="Google Maps API – infowindows">infowindows</a>. Maybe you want to start drawing lines and shapes on it.</p>
<p>Supposing I have two markers, and I just want to draw a line connecting them.</p>
<pre style="font-size:larger;">&lt;script type="text/javascript"&gt;
	function initialize() {
		var homeLatlng = new google.maps.LatLng(51.476706,0);

		var map = new google.maps.Map(document.getElementById("map"), {
			zoom: 15,
			center: homeLatlng,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		});

		// add start marker
		var startLatLng = new google.maps.LatLng(51.482051,0.001436);

		var startMarker = new google.maps.Marker({
			position: startLatLng, 
			map: map, 
			icon: 'http://maps.google.co.uk/intl/en_ALL/mapfiles/ms/micons/green-dot.png'
		});

		// add end marker
		var endLatLng = new google.maps.LatLng(51.473271,0.003195);

		var endMarker = new google.maps.Marker({
			position: endLatLng, 
			map: map, 
			icon: 'http://maps.google.co.uk/intl/en_ALL/mapfiles/ms/micons/red-dot.png'
		});

		// draw the route
		var route = new google.maps.Polyline({
			path: [startLatLng, endLatLng],
			strokeColor: "#FF0000",
			strokeOpacity: 1.0,
			strokeWeight: 4,
			map: map
		});	
	}

	google.maps.event.addDomListener(window, 'load', initialize);
&lt;/script&gt;</pre>
<p>Which gives us this simple map here:<br />
<a href="http://duncan99.files.wordpress.com/2013/01/polyline1.png"><img class="aligncenter size-full wp-image-1609" alt="polyline1" src="http://duncan99.files.wordpress.com/2013/01/polyline1.png?w=600&#038;h=479" width="600" height="479" /></a></p>
<p>The important part to note here is the path attribute in the Polyline Options. The [ ] indicates it is an array, and indeed you can make an array of many coordinates:</p>
<pre style="font-size:larger;">	function initialize() {
		var homeLatlng = new google.maps.LatLng(51.476706,0);

		var map = new google.maps.Map(document.getElementById("map"), {
			zoom: 15,
			center: homeLatlng,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		});

		// add start marker
		var startMarker = new google.maps.Marker({
			position: new google.maps.LatLng(51.482238,0.001581), 
			map: map, 
			icon: 'http://maps.google.co.uk/intl/en_ALL/mapfiles/ms/micons/green-dot.png'
		});

		// add end marker
		var endMarker = new google.maps.Marker({
			position: new google.maps.LatLng(51.481577,-0.0022), 
			map: map, 
			icon: 'http://maps.google.co.uk/intl/en_ALL/mapfiles/ms/micons/red-dot.png'
		});

		// create an array of coordinates
		var arrCoords = [
			new google.maps.LatLng(51.482238,0.001581),
			new google.maps.LatLng(51.473364,0.011966),
			new google.maps.LatLng(51.471974,-0.000651),
			new google.maps.LatLng(51.472108,-0.002196),
			new google.maps.LatLng(51.474995,-0.003827),
			new google.maps.LatLng(51.476492,-0.005629),
			new google.maps.LatLng(51.477855,-0.006058),
			new google.maps.LatLng(51.478443,-0.007045),
			new google.maps.LatLng(51.479298,-0.007861),
			new google.maps.LatLng(51.481202,-0.002136),
			new google.maps.LatLng(51.481577,-0.0022)
		];

		// draw the route
		var route = new google.maps.Polyline({
			path: arrCoords,
			strokeColor: "#FF0000",
			strokeOpacity: 1.0,
			strokeWeight: 4,
			map: map
		});	
	}

	google.maps.event.addDomListener(window, 'load', initialize);</pre>
<p>Which gives you something more useful (if you were wanting to map the boundary of Greenwich Park that is):</p>
<p><a href="http://duncan99.files.wordpress.com/2013/01/polyline2.png"><img class="aligncenter size-full wp-image-1610" alt="polyline2" src="http://duncan99.files.wordpress.com/2013/01/polyline2.png?w=599&#038;h=479" width="599" height="479" /></a></p>
<p>One important detail with polylines is if we want the lines to be <a href="http://en.wikipedia.org/wiki/Geodesic">geodesic</a> or not.  When drawing lines, by default they are in a straight line on a 2D surface.  But the earth&#8217;s surface is curved.  What this means is if you want the <em>shortest</em> line between two points, the line might be slightly curved.  This is probably easier to illustrate than to explain.</p>
<h3>Example One</h3>
<p><a href="http://duncan99.files.wordpress.com/2013/02/polylines1.png"><img class="aligncenter size-full wp-image-1616" alt="polylines1" src="http://duncan99.files.wordpress.com/2013/02/polylines1.png?w=503&#038;h=518" width="503" height="518" /></a></p>
<p>Here I&#8217;m drawing one blue vertical line, and several red diagonal lines, using this code:</p>
<pre style="font-size:larger;">
	function initialize() {
		var line;
		var homeLatlng = new google.maps.LatLng(0,0);
				
		var map = new google.maps.Map(document.getElementById("map"), {
			zoom: 2,
			center: homeLatlng,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		});
		
		for (var i = 0; i &lt; 60; i+= 5) {
			line = new google.maps.Polyline({
				path: [homeLatlng, new google.maps.LatLng(i,170)],
				strokeColor: "#FF0000",
				strokeOpacity: 1.0,
				strokeWeight: 1,
				geodesic: false,
				map: map
			});
		}
		
		// for vertical line just draw one line
		line = new google.maps.Polyline({
			path: [homeLatlng, new google.maps.LatLng(85,0)],
			strokeColor: "#0000FF",
			strokeOpacity: 1.0,
			strokeWeight: 1,
			geodesic: false,
			map: map
		});
	}
	
	google.maps.event.addDomListener(window, 'load', initialize);</pre>
<p>Notice I&#8217;m specifying <em>geodesic: false</em> &#8211; we don&#8217;t want geodesic curved lines.</p>
<p>Also one other difference over earlier examples.  We need to use the <a href="https://developers.google.com/maps/documentation/javascript/geometry">Geometry library</a> from Google, so have to add this as a parameter when calling their script:</p>
<pre style="font-size:larger;">&lt;script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&amp;libraries=geometry"&gt;&lt;/script&gt;</pre>
<h3>Example Two</h3>
<p>This time simply change the <em>geodesic</em> attribute to <em>true</em> in both places we create polylines; all the other code is identical.</p>
<p><a href="http://duncan99.files.wordpress.com/2013/02/polylines2.png"><img class="aligncenter size-full wp-image-1617" alt="polylines2" src="http://duncan99.files.wordpress.com/2013/02/polylines2.png?w=506&#038;h=521" width="506" height="521" /></a></p>
<p>The vertical line and the one horizontal line don&#8217;t look any different, but the diagonal lines take a curved route which is approximately the shortest distance, following the earth&#8217;s curve, between the two points.  Of course on shorter distances you&#8217;re unlikely to notice any difference between the straight and curved lines, so for the most part you&#8217;ll typically use straight lines.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/duncan99.wordpress.com/1480/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/duncan99.wordpress.com/1480/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=duncan99.wordpress.com&#038;blog=4274552&#038;post=1480&#038;subd=duncan99&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://duncan99.wordpress.com/2013/02/12/google-maps-api-polylines/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/e5594b71e9f54f3e73f6294b054f5616?s=96&#38;d=http%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">duncan</media:title>
		</media:content>

		<media:content url="http://duncan99.files.wordpress.com/2013/01/polyline1.png" medium="image">
			<media:title type="html">polyline1</media:title>
		</media:content>

		<media:content url="http://duncan99.files.wordpress.com/2013/01/polyline2.png" medium="image">
			<media:title type="html">polyline2</media:title>
		</media:content>

		<media:content url="http://duncan99.files.wordpress.com/2013/02/polylines1.png" medium="image">
			<media:title type="html">polylines1</media:title>
		</media:content>

		<media:content url="http://duncan99.files.wordpress.com/2013/02/polylines2.png" medium="image">
			<media:title type="html">polylines2</media:title>
		</media:content>
	</item>
		<item>
		<title>Converting UUID to Base36</title>
		<link>http://duncan99.wordpress.com/2013/01/22/converting-uuid-to-base36/</link>
		<comments>http://duncan99.wordpress.com/2013/01/22/converting-uuid-to-base36/#comments</comments>
		<pubDate>Tue, 22 Jan 2013 10:40:46 +0000</pubDate>
		<dc:creator>duncan</dc:creator>
				<category><![CDATA[Coldfusion]]></category>
		<category><![CDATA[base16]]></category>
		<category><![CDATA[base36]]></category>
		<category><![CDATA[biginteger]]></category>
		<category><![CDATA[cfml]]></category>
		<category><![CDATA[conversion]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://duncan99.wordpress.com/?p=1555</guid>
		<description><![CDATA[Base 36 I needed to generate a random unique string of no more than 30 characters length for integrating with an external API.  Usually for something like this we&#8217;d use a UUID/GUID, which are 36 characters long (or 35 in ColdFusion).  A colleague came up with the idea of taking that and converting it to [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=duncan99.wordpress.com&#038;blog=4274552&#038;post=1555&#038;subd=duncan99&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<div style="float:right;text-align:center;"><a title="Base36 by duncan, on Flickr" href="http://www.flickr.com/photos/duncan/8402036415/"><img alt="Base36" src="http://farm9.staticflickr.com/8374/8402036415_c0358b0f70_n.jpg" width="320" height="320" /></a><br />
Base 36</div>
<p>I needed to generate a random unique string of no more than 30 characters length for integrating with an external API.  Usually for something like this we&#8217;d use a UUID/GUID, which are 36 characters long (or 35 in ColdFusion).  A colleague came up with the idea of taking that and converting it to <a href="http://en.wikipedia.org/wiki/Base32">Base 32</a>.  He was using C# and <a href="http://stackoverflow.com/questions/641361/base32-decoding/7135008#7135008">this class</a>, but then this part of the work got transferred to the ColdFusion team, so here&#8217;s the approach I took.</p>
<p>Firstly, a <a href="http://en.wikipedia.org/wiki/Universally_unique_identifier">UUID</a> is a hexadecimal representation of a 128-bit number.  Being hexadecimal that&#8217;s <a href="http://en.wikipedia.org/wiki/Hexadecimal">Base 16</a> obviously; the characters 0-9A-F.</p>
<p>A 128-bit number = 2<sup>^128</sup>, which is a very big number (340,282,366,920,938,463,463,374,607,431,768,211,456 possible values).  ColdFusion can struggle with integers this size in certain functions, e.g. <a href="http://www.bennadel.com/blog/901-Exploring-ColdFusion-InputBaseN-And-FormatBaseN-Functions.htm">InputBaseN (and its counterpart FormatBaseN)</a>, otherwise that would be ideal for what I&#8217;m trying to do here</p>
<p>There&#8217;s already<a href="http://www.cflib.org/udf/nBase36"> a function in CFLib</a> which could do this, but it&#8217;s compatible with ColdFusion 5, i.e. it&#8217;s not got access to any of the underlying Java classes which CFMX does.  My colleague Adam also wrote a different function which can <a href="http://www.cflib.org/udf/baseMToBaseN">convert between any two bases</a>, but it&#8217;s more fully-featured than I require as well.</p>
<p>UUID&#8217;s also contain hyphens.  Typically a UUID format is in a <code>8-4-4-4-12</code> pattern, i.e. the string is 36 characters long.  ColdFusion does it differently; <code>8-4-4-16</code>, only 35 characters long.  Apparently this difference was a mistake, which they <a href="http://jochem.vandieten.net/2011/05/05/the-definitive-guide-to-coldfusion-uuids/">didn&#8217;t want to amend later due to backwards-compatibility</a>. However for the purposes of this code, I don&#8217;t care either way, I just want to get rid of the hyphen separators.</p>
<p>So, step 1 is remove the hyphens from a UUID:</p>
<pre style="font-size:larger;">&lt;cfset strUUID = createUUID()&gt;
&lt;cfset strUUID = replace(strUUID, "-", "", "ALL")&gt;</pre>
<p>Now I want to turn this hexadecimal string into a <a href="http://docs.oracle.com/javase/1.4.2/docs/api/java/math/BigInteger.html">BigInteger</a>, which is the Java class which can deal with numbers this size (Integer only goes up to 2<sup>^31</sup>-1, Long goes up to 2<sup>^63</sup>-1, so BigInteger it has to be).</p>
<pre style="font-size:larger;">&lt;cfset bigInt = createObject("java", "java.math.BigInteger").init(strUUID, 16)&gt;</pre>
<p>So we use the BigInteger constructor, specifying our string and the Base 16 radix as the second parameter.</p>
<p>Step 3, we want to then convert that BigInteger to <a href="http://en.wikipedia.org/wiki/Base_36">Base 36</a>. This is the characters A-Z0-9, and is <em>&#8216;the most compact case-insensitive alphanumeric numeral system using ASCII characters&#8217;</em>. Which I took to be a good thing; the advantage that Base 32 (that my colleague had chosen) would have given is it eliminates certain characters which might be easily-confused if you were reading the values after encoding in that base. So it&#8217;s ideal for generating codes used for humans, but that wasn&#8217;t going to be an issue here, so I chose Base 36 instead.</p>
<pre style="font-size:larger;">&lt;cfset strBase36 = bigInt.toString(36)&gt;</pre>
<p>Putting it all together:</p>
<pre style="font-size:larger;">&lt;cfset strUUID = createUUID()&gt;
&lt;cfset strUUID = replace(strUUID, "-", "", "ALL")&gt;
&lt;cfset bigInt = createObject("java", "java.math.BigInteger").init(strUUID, 16)&gt;
&lt;cfset strBase36 = bigInt.toString(36)&gt;

&lt;cfoutput&gt;
strUUID: #strUUID#, #len(strUUID)#&lt;br&gt;
strBase36: #strBase36#, #len(strBase36)#
&lt;/cfoutput&gt;</pre>
<p>Gives me something like:</p>
<blockquote><p>strUUID: AFA64721B8AC6F8CD055DE2527EB20F9, 32<br />
strBase36: aecxzys9dnwydn6ejgkxwgb95, 25</p></blockquote>
<p>PS: apologies to <a href="http://www.base36.com/it-consulting-blog/bid/244319/Base36-The-History-of-Our-Company-s-Name">Base36</a> (the company) for borrowing their funky (and let&#8217;s be honest, better-executed) Base36 mosaic idea.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/duncan99.wordpress.com/1555/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/duncan99.wordpress.com/1555/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=duncan99.wordpress.com&#038;blog=4274552&#038;post=1555&#038;subd=duncan99&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://duncan99.wordpress.com/2013/01/22/converting-uuid-to-base36/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/e5594b71e9f54f3e73f6294b054f5616?s=96&#38;d=http%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">duncan</media:title>
		</media:content>

		<media:content url="http://farm9.staticflickr.com/8374/8402036415_c0358b0f70_n.jpg" medium="image">
			<media:title type="html">Base36</media:title>
		</media:content>
	</item>
		<item>
		<title>ColdFusion cfloop versus cfscript for loop performance</title>
		<link>http://duncan99.wordpress.com/2012/10/18/coldfusion-cfloop-versus-cfscript-for-loop-performance/</link>
		<comments>http://duncan99.wordpress.com/2012/10/18/coldfusion-cfloop-versus-cfscript-for-loop-performance/#comments</comments>
		<pubDate>Thu, 18 Oct 2012 19:01:57 +0000</pubDate>
		<dc:creator>duncan</dc:creator>
				<category><![CDATA[Coldfusion]]></category>
		<category><![CDATA[cfml]]></category>
		<category><![CDATA[linkedin]]></category>

		<guid isPermaLink="false">http://duncan99.wordpress.com/?p=1537</guid>
		<description><![CDATA[I&#8217;m sure most web developers are aware that, in Javascript, it&#8217;s generally considered best practice to do this: for (var i = 0, len = array.length; i &#60; len; i++) { } instead of this: for (var i = 0; i &#60; array.length; i++) { } The theory being that you improve performance by caching [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=duncan99.wordpress.com&#038;blog=4274552&#038;post=1537&#038;subd=duncan99&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>I&#8217;m sure most web developers are aware that, in Javascript, it&#8217;s generally considered best practice to do this:</p>
<pre style="font-size:larger;">for (var i = 0, len = array.length; i &lt; len; i++) { }</pre>
<p>instead of this:</p>
<pre style="font-size:larger;">for (var i = 0; i &lt; array.length; i++) { }</pre>
<p>The theory being that you improve performance by caching the array length once, instead of each time you iterate over the loop (although it&#8217;s open to debate how important this is; it really <a href="http://www.erichynds.com/javascript/javascript-loop-performance-caching-the-length-property-of-an-array/">only benefits IE</a>).</p>
<p>I decided to see if there was any benefit in doing the same thing with array loops in ColdFusion. Initially just tested with CFML, then again with CFScript, to see if there were any differences.</p>
<pre style="font-size:larger;">&lt;!--- start with a blank file each time ---&gt;
&lt;cfif fileExists("arraylen.txt")&gt;
	&lt;cffile action="delete" file="arraylen.txt"&gt;
&lt;/cfif&gt;

&lt;cfloop index="j" from="1" to="1000"&gt;
	&lt;!--- create a large array to loop over later ---&gt;
	&lt;cfset myArray = []&gt;	
	&lt;cfloop index="i" from="1" to="10000000"&gt;&lt;cfset arrayAppend(myArray, "")&gt;&lt;/cfloop&gt;

	&lt;cfscript&gt;
		// Method 1
		tick = GetTickCount();

		for (i=1; i &lt;= arrayLen(myArray); i++) {}

		recordTime(
			type	= "CFScript (arrayLen)",
			tick	= tick
		);

		// Method 2
		tick = GetTickCount();

		len = arrayLen(myArray);

		for (i=1; i &lt;= len; i++) {}

		recordTime(
			type	= "CFScript (var'ed)",
			tick	= tick
		);
	&lt;/cfscript&gt;

	&lt;!--- Method 1 ---&gt;
	&lt;cfset tick = GetTickCount()&gt;

	&lt;cfloop index="i" from="1" to="#arrayLen(myArray)#"&gt;&lt;/cfloop&gt;

	&lt;cfset recordTime(
		type	= "CFML (arrayLen)",
		tick	= tick
	)&gt;

	&lt;!--- Method 2 ---&gt;
	&lt;cfset tick = GetTickCount()&gt;

	&lt;cfset len = arrayLen(myArray)&gt;

	&lt;cfloop index="i" from="1" to="#len#"&gt;&lt;/cfloop&gt;

	&lt;cfset recordTime(
		type	= "CFML (var'ed)",
		tick	= tick
	)&gt;
&lt;/cfloop&gt;

&lt;cffunction name="recordTime" output="false" returntype="void"&gt;
	&lt;cfargument name="type" type="string" required="true"&gt;
	&lt;cfargument name="tick" type="numeric" required="true"&gt;

	&lt;cfset var tock = GetTickCount()&gt;
	&lt;cfset var time = tock - arguments.tick&gt;

	&lt;cffile action="append" output="#arguments.type##chr(9)##time#ms" file="arraylen.txt"&gt;
&lt;/cffunction&gt;</pre>
<p>What I did find was that the two methods, of either calculating arrayLen() within the FOR loop, or storing it as a variable, hardly differed at all in performance.</p>
<p>However there was a big difference in performance between CFML and CFScript. In this case, the looping was much slower in CFScript. This isn&#8217;t something new, I&#8217;m sure I&#8217;ve heard this before, but it was an interesting reminder for me that sometimes it&#8217;s not always best to write everything in CFScript.</p>
<p>So here&#8217;s the results showing the average times from running this 1000 times:</p>
<p><a href="http://duncan99.files.wordpress.com/2012/10/arraylen.png"><img src="http://duncan99.files.wordpress.com/2012/10/arraylen.png?w=481&#038;h=289" alt="" title="arraylen" width="481" height="289" class="aligncenter size-full wp-image-1543" /></a></p>
<table>
<tr>
<th>CFML (arrayLen)</th>
<td>257.883ms</td>
</tr>
<tr>
<th>CFML (var&#8217;ed)</th>
<td>258.284ms</td>
</tr>
<tr>
<th>CFScript (arrayLen)</th>
<td>1259.294ms</td>
</tr>
<tr>
<th>CFScript (var&#8217;ed)</th>
<td>1180.07ms</td>
</tr>
</table>
<p>As we can see, the difference between caching the array length in a variable, or using arrayLen() for the loop limit, is negligible in CFML, less than 0.5 of a millisecond after 1000 iterations!</p>
<p>However in CFScript, it seems slightly quicker to use a variable instead of referring to arrayLen() within the iterator.  But not so much that I&#8217;d say I&#8217;d favour one method over the other.  Although I&#8217;ll certainly think twice before writing array loops in CFScript instead of CFML&hellip; although in reality the difference in performance is relatively minor (unless you&#8217;re working on massive arrays and/or have a high-traffic application).</p>
<p>PS: I&#8217;m running this on Adobe ColdFusion 9,0,1,274733 on Windows 7, <a href="http://www.urbandictionary.com/define.php?term=YMMV">YMMV</a> <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/duncan99.wordpress.com/1537/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/duncan99.wordpress.com/1537/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=duncan99.wordpress.com&#038;blog=4274552&#038;post=1537&#038;subd=duncan99&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://duncan99.wordpress.com/2012/10/18/coldfusion-cfloop-versus-cfscript-for-loop-performance/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/e5594b71e9f54f3e73f6294b054f5616?s=96&#38;d=http%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">duncan</media:title>
		</media:content>

		<media:content url="http://duncan99.files.wordpress.com/2012/10/arraylen.png" medium="image">
			<media:title type="html">arraylen</media:title>
		</media:content>
	</item>
		<item>
		<title>Regex to find 6 repeating characters</title>
		<link>http://duncan99.wordpress.com/2012/09/11/regex-to-find-6-repeating-characters/</link>
		<comments>http://duncan99.wordpress.com/2012/09/11/regex-to-find-6-repeating-characters/#comments</comments>
		<pubDate>Tue, 11 Sep 2012 12:49:22 +0000</pubDate>
		<dc:creator>duncan</dc:creator>
				<category><![CDATA[Regular Expressions]]></category>
		<category><![CDATA[back references]]></category>
		<category><![CDATA[linkedin]]></category>
		<category><![CDATA[regex]]></category>
		<category><![CDATA[regular expression]]></category>
		<category><![CDATA[regular expressions]]></category>

		<guid isPermaLink="false">http://duncan99.wordpress.com/?p=1525</guid>
		<description><![CDATA[I wanted to check our codebase for where we had six repeating characters in HTML and CSS for colours, e.g. #FFFFFF for white.  Here&#8217;s the regular expression for it, basically blogged here so I can remember where to find it later: ([a-fA-F0-9])\1{5} So [a-fA-F0-9] looks for a single character that is one of the letters A [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=duncan99.wordpress.com&#038;blog=4274552&#038;post=1525&#038;subd=duncan99&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>I wanted to check our codebase for where we had six repeating characters in HTML and CSS for colours, e.g. #FFFFFF for white.  Here&#8217;s the regular expression for it, basically blogged here so I can remember where to find it later:</p>
<pre style="font-size:larger;">([a-fA-F0-9])\1{5}</pre>
<p>So <strong>[a-fA-F0-9]</strong> looks for a single character that is one of the letters A &#8211; F (only need to go up to F because we&#8217;re dealing with hexadecimal numbers), or the digits 0 &#8211; 9.</p>
<p>The<strong> ( )</strong> parentheses around that turns it into a backreference.</p>
<p>The <strong>\1</strong> then refers to that backreferenced matched, and the <strong>{5}</strong> says to match it exactly 5 times.</p>
<p>So it&#8217;ll find where there&#8217;s a single matching character that is then repeated five times.</p>
<p>What I was doing this for was to replace all six character codes (that repeat) for colours with three character codes (because #FFF is equivalent to #FFFFFF). So to then replace it, I used the following (in Eclipse):</p>
<pre style="font-size:larger;">Find: ([a-fA-F0-9])\1{5}
Replace with: \1\1\1</pre>
<p>We can also modify the regular expression so it also catches colours like #FF0000 or #33FF99, where we have three repeating sets of identical digits.  These can also be shortened, to #F00 or #3F9.</p>
<p>This modified regular expression will cover this too.  In this case we&#8217;re looking three times for a single character that gets repeated once each time.  We then replace with just the three different single characters, ignore the repeating characters:</p>
<pre style="font-size:larger;">Find: ([a-fA-F0-9])\1{1}([a-fA-F0-9])\1{1}([a-fA-F0-9])\1{1}
Replace with: \1\2\3</pre>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/duncan99.wordpress.com/1525/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/duncan99.wordpress.com/1525/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=duncan99.wordpress.com&#038;blog=4274552&#038;post=1525&#038;subd=duncan99&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://duncan99.wordpress.com/2012/09/11/regex-to-find-6-repeating-characters/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/e5594b71e9f54f3e73f6294b054f5616?s=96&#38;d=http%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">duncan</media:title>
		</media:content>
	</item>
		<item>
		<title>ColdFusion regular expression backreferences and numeric strings</title>
		<link>http://duncan99.wordpress.com/2012/03/12/coldfusion-regular-expression-backreferences-and-numeric-strings/</link>
		<comments>http://duncan99.wordpress.com/2012/03/12/coldfusion-regular-expression-backreferences-and-numeric-strings/#comments</comments>
		<pubDate>Mon, 12 Mar 2012 11:00:07 +0000</pubDate>
		<dc:creator>duncan</dc:creator>
				<category><![CDATA[Coldfusion]]></category>
		<category><![CDATA[backreference]]></category>
		<category><![CDATA[backreferences]]></category>
		<category><![CDATA[cfml]]></category>
		<category><![CDATA[linkedin]]></category>
		<category><![CDATA[regex]]></category>
		<category><![CDATA[regular expression]]></category>
		<category><![CDATA[regular expressions]]></category>

		<guid isPermaLink="false">http://duncan99.wordpress.com/?p=1516</guid>
		<description><![CDATA[Supposing you have a string that starts with a number, e.g. &#8220;25% discount this weekend&#8221;, and you&#8217;re using that along with a regular expression.  If you&#8217;ve got a backreference immediately prior to that &#8220;25%&#8230;&#8221;, ColdFusion treats it as \125 instead of \1.  For instance: &#60;cfset myString = "25% Discount this weekend"&#62; &#60;cfset originalString = "Look [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=duncan99.wordpress.com&#038;blog=4274552&#038;post=1516&#038;subd=duncan99&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Supposing you have a string that starts with a number, e.g. &#8220;25% discount this weekend&#8221;, and you&#8217;re using that along with a regular expression.  If you&#8217;ve got a backreference immediately prior to that &#8220;25%&#8230;&#8221;, ColdFusion treats it as \125 instead of \1.  </p>
<p>For instance:</p>
<pre style="font-size:larger;">
&lt;cfset myString = "25% Discount this weekend"&gt;

&lt;cfset originalString = "Look out for our special offers, including XXX and much more"&gt;

&lt;cfset newString = reReplace(originalString, "(.*)XXX(.*)", "\1#myString#\2")&gt;

&lt;cfoutput&gt;#newString#&lt;/cfoutput&gt;
</pre>
<p>This just outputs:<br />
<strong>% Discount this weekend and much more</strong><br />
as it thinks that you&#8217;re trying to do \125 instead of \1 followed by &#8220;25%&#8230;&#8221;</p>
<p>To get around this, you can use \E to separate the backreference from the rest of the string.<br />
\E is meant to <a href="http://help.adobe.com/en_US/ColdFusion/9.0/Developing/WSc3ff6d0ea77859461172e0811cbec22c24-7e91.html">indicate when you&#8217;ve reached the end of an uppercase or lowercase block</a> as set by \U or \L.  However in this case it simply indicates to the regular expression process where the end of the backreference occurs.</p>
<pre style="font-size:larger;">
&lt;cfset newString = reReplace(originalString, "(.*)XXX(.*)", "\1\E#myString#\2")&gt;

&lt;cfoutput&gt;#newString#&lt;/cfoutput&gt;
</pre>
<p>This time it correctly outputs:<br />
<strong>Look out for our special offers, including 25% Discount this weekend and much more</strong></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/duncan99.wordpress.com/1516/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/duncan99.wordpress.com/1516/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=duncan99.wordpress.com&#038;blog=4274552&#038;post=1516&#038;subd=duncan99&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://duncan99.wordpress.com/2012/03/12/coldfusion-regular-expression-backreferences-and-numeric-strings/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/e5594b71e9f54f3e73f6294b054f5616?s=96&#38;d=http%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">duncan</media:title>
		</media:content>
	</item>
	</channel>
</rss>
