Quick guide to Geolocation in Javascript

In some modern browsers, such as Chrome and Firefox you can access the geolocation of the device. That is, where the device is physically located.

The main function for achieving this is getCurrentPosition, which doesn’t return a position as you might expect. Rather, it takes a callback (and optionally a second if you want to handle error conditions).

I’ve put together a small example page showing this, which I’ll now walk through.

In the example, when the user clicks on the button on the page it will attempt to get the physical location of the device. This may or may not work for several reasons. If it doesn’t work then the browser may not support it, or the user may refuse to give permission to the site, or the geolocation service may not be working.

This first bit of code checks to see if the browser supports the geolocation API and if it does calls the function to get the location passing in the callbacks for success and error handling.

if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
} else {
    displayErrorMessage("The browser does not support the Geolocation API.");
}

In this small example, the successCallback simply fills various spans with the results in the position and creates a URL that links to google maps to display a pin at the coordinates.

function successCallback(position) {
    $("#latitude").html(position.coords.latitude);
    $("#longitude").html(position.coords.longitude);
    $("#accuracy").html(position.coords.accuracy);
    $("#displayMap").attr("href", "http://maps.google.com/?q=" + position.coords.latitude + "," + position.coords.longitude);
    $("#displayMap").removeClass("disabled");
}

The position has a timestamp and a set of coordinates. Since the geolocation may be cached the timestamp will give you an indication of how old the geolocation is.

The coords gives you various bits of information about the geolocation. The three values that will always be available are latitude, longitude and accuracy. The other values (such as altitude, heading and speed) may be nullable. The accuracy is in meters and can be used to gauge how good the lat/long is. The Lat/Long is in WGS84 decimal degrees.

In the event of an error, the errorCallback will receive some indication about what went wrong. The most common may be that the permission was denied, but other potential errors exist.

function errorCallback(error) {
    switch (error.code) {
        case error.PERMISSION_DENIED:
            displayErrorMessage("The request was denied. If a message seeking persmission was not displayed then check your browser settings.");
            break;
        case error.POSITION_UNAVAILABLE:
            displayErrorMessage("The position of the device could not be determined. For instance, one or more of the location providers used in the location acquisition process reported an internal error that caused the process to fail entirely.");
            break;
        case error.TIMEOUT:
            displayErrorMessage("The request to get user location timed out before the operation could complete.");
            break;
        case error.UNKNOWN_ERROR:
            displayErrorMessage("Something unexpected happened.");
            break;
    }
}

 

How your browser reacts to requests for geolocation

Your browser may give you some form of alert to indicate that the site is requesting the geolocation. Chrome, for example, displays a bar just under the omnibox

Chome asks if it is okay to use geolocation

If a site has permission to get the geolocation then the icon above will be displayed in the omnibox to the right of the URL. If not, the icon will have a red cross over it. You can click this icon to change the settings at any time.

 

Finally, if you want to read the spec in full, it is available here: http://www.w3.org/TR/geolocation-API/

Pomodoro

I keep hearing about friends using The Pomodoro Technique and I’ve decided I really need to just try it out for myself. I’m not yet sure if it will work for me, but I’ve been hearing positive things about it.

To that end I set myself the task of a small project using it, that is to create a web page with a pomodoro timer with a visible indicator of time left and that makes a noise when the timer expires. The final pomodoro is to write up this blog post.

This task has a mix of things I already know about (putting together a web page with HTML, CSS, JavaScript and jQuery) and things I would have to look up (like how to get a web page to emit a sound at a given point, have it respond to events at timed intervals, and deploy it to the web via Amazon’s AWS).

What I found was that 25 minutes actually goes past very quickly. Secondly, and this is more because it is the Christmas holidays, I still need to discipline myself not to jump to Facebook or Twitter each time my phone beeps or chirrups a notification at me. Similarly, in work I would probably have to discipline myself not to jump to Outlook or Skype when they pop up notifications.

On the whole, it looks like it could be fairly advantageous and I’ll continue to see if it helps productivity.

For the moment, if you do want to have a look at the very simple pomodoro timer that I created, then you can access it here: http://pomodoro.colinmackay.co.uk – I’m also happy to take suggestions on improvements if you think it could be made better.

Kendo UI: parse – preprocessing data

When retrieving data, it may not be formatted as you would need it. Most obviously, dates are the most likely candidates as the grid can work with them much more easily if they are javaScript Date objects rather than any text or numeric representation. It should be noted however, that if by simply telling the dataSource configuration that the schema of the a specific field is a date then it may be able to work out the format for itself and you don’t need a parse function to help. However, for this example, assume you must convert the type of the value.

dataSource : schema : parse

The dataSource configuration allows you to specify a function that is called when the data needs to be preprocessed in some way.

The parse function takes a parameter where by it passes the object containing the data. The function must return the processed data. In my example I’ve simply replaced the values in the existing structure with the processed version.

function preprocessData(data) {
  // iterate over all the data elements replacing the Date with a version
  // that Kendo can work with.
    $.each(data, function(index, item){
      item.Date = kendo.parseDate(item.Date, "yyyy-MM-dd");
    });
    return data;
}

The JSON structure contains a date in a string with a specific format containing a 4 digit year, followed by a two digit month, followed by a two digit day, separated by dashes. However, the grid can work with dates more easily if they are Date objects, which is what the kendo.parseDate() function returns.

Dealing with percentages

In a previous post I mentioned that you can format a number as a percentage by using a specific format in the kendo.toString() function call. Unfortunately, that may not be the best solution in all cases. If your data is not going to be filtered and it is in range of 0 to 1 representing 0% to 100% then that solution is fine. However, if you want to filter on the data then you probably don’t want to do that, as you’d have to enter set up the filter in the same way as the source data – and it is not intuative for the user to have to type “”0.5” when they need “50%”.

What you can do instead is ensure that the data is in the form that 100.0 is 100%, and so forth. You can use the parse function to coerce the data if you need to do that. Once you have this the filters become more intuative from the user’s perspective. Also, instead of using the built in format for parsing percentages you will need to use your own, such as “0.0”, which ensures that the value has one digit after decimal point. For example:

template:"#= kendo.toString(Rpi, \"0.0\") #%"

Filtering on a percentage column

The grid configuration

$(function(){
  var data = getData(); // From the economic-data.js file
  $('#MyGrid').kendoGrid({
    dataSource: {
      data: data,
      pageSize: 10,
      schema: {
           parse: function(data){
             return preprocessData(data);
           },
          model: {
          fields: {
            Date: {type: "date" },
            Rpi: {type: "number" },
            Cpi: {type: "number" },
            BoeRate: {type: "number" }
          }
        }
      }
    },
    filterable: true,
    columnMenu: false,
    sortable: true,
    pageable: true,
    scrollable: false,
    columns: [ 
      { field: "Date", template: "#= kendo.toString(Date, \"MMM yyyy\") #" }, 
      { field: "Rpi", title: "Inflation (RPI)", template:"#= kendo.toString(Rpi, \"0.0\") #%" }, 
      { field: "Cpi", title: "Inflation (CPI)", template:"#= (Cpi !== null ? kendo.toString(Cpi, \"0.0\")+\"%\" : \"-\") #" },
      { field: "BoeRate", title: "Base Rate", template:"#= kendo.toString(BoeRate, \"0.0\") #%" }
    ]
  });
});

More information

For this post the data is a mash up of UK Inflation data since 1948 and Bank of England Base Rates since 1694. I’ve only used the intersecting dates of both datasets.

The economic-data.js file is available as a github gist.

There is also a working example of this code.

Kendo UI: Paging and accessing the filtered results in javaScript

Moving on slightly from my last post on the Kendo UI Grid we’re going to take a wee look at paging and accessing the results of the filter in javaScript.

pageable : true

By default paging is turned off. This means that when the grid is rendered you get all the data displayed in one go. If the amount of data is small then this
may be fine. However, if the amount of data runs into the hundreds of rows (or more) then you’ll probably want to turn paging on in order to make the display of the data more manageable for the user and potentially to reduce the amount of data send to the browser (but that part is for another day – in this example I’ll be using the same data set as previously which is loaded all at once).

To enable paging add to the configuration pageable : true and also remember to add in to the dataSource part of the configuration the
pageSize that you want.

If you forget to put the pageSize in then the grid will display with all the elements, but the paging navigation bar will display a message such as “NaN – NaN of 150 items”

scrollable : false

By default the grid is scrollable. This is useful if you have something to scroll, such as the virtualised scrolling feature. But for the paging in this example, the scroll bar is simply displayed but not enabled.

To turn off the scrollbar, in the configuration set scrollable : false and the scroll bar will be removed.

Getting the filtered results in JavaScript

It is possible to get the results of the filter out of the grid. It isn’t actually a direct feature of the grid (or the dataSource) but it is possible in a round about sort of way.

Essentially, what needs to happen is that filter object in the grid is used to query the data all over again to produce a second result set that can be used directly in JavaScript.

In the example below, I’ve got the results of the filter being rendered into a unordered list block.

It works but first getting hold of the grid’s data source, getting the filter and the data, creating a new query with the data and applying the filter to it. While this does result in getting the results of the filter it does have the distinct disadvantage of processing the filter operation twice.

function displayFilterResults() {
  // Gets the data source from the grid.
  var dataSource = $("#MyGrid").data("kendoGrid").dataSource;

  // Gets the filter from the dataSource
  var filters = dataSource.filter();

  // Gets the full set of data from the data source
  var allData = dataSource.data();

  // Applies the filter to the data
  var query = new kendo.data.Query(allData);
  var filteredData = query.filter(filters).data;

  // Output the results
  $('#FilterCount').html(filteredData.length);
  $('#TotalCount').html(allData.length);
  $('#FilterResults').html('');
  $.each(filteredData, function(index, item){
    $('#FilterResults').append('<li>'+item.Site+' : '+item.Visitors+'</li>')
  });
}

The results look like this:

The filter results in 12 of 150 rows returned.

National Galleries of Scotland (Edinburgh sites) : 1281465
Edinburgh Castle (Historic Scotland) : 1210248
Kelvingrove Art Gallery & Museum (Glasgow) : 1070521
Royal Botanic Garden Edinburgh : 707244
Gallery of Modern Art (Glasgow Museums) : 490872
People's Palace (Glasgow Museums) : 245770
Burrell Collection (Glasgow Museums) : 187756
Museum of Transport (Glasgow Museums) : 160571
St Mungo Museum of Religious Art (Glasgow Museums) : 143017
Provand's Lordship (Glasgow Museums) : 107044
Scotland Street School Museum (Glasgow Museums) : 49346
Glasgow Museums Resource Centre : 9059

Full grid configuration

Here is the full configuration of the grid for this example:

$(function(){
  var data = getData(); // From the bva-data.js file
  $('#MyGrid').kendoGrid({
    dataSource: {
      data: data,
      pageSize: 10,
      schema: {
        model: {
          fields: {
            Site: {type: "string" },
            Visitors: {type: "number" },
            FreeCharge: {type: "string" },
            Change: {type: "number" }
          }
        }
      }
    },
    filterable: true,
    columnMenu: false,
    sortable: true,
    pageable: true,
    scrollable: false,
    columns: [ 
      { field: "Site" }, 
      { field: "Visitors" }, 
      { field: "FreeCharge" },
      { field: "Change", template: "#= kendo.toString(Change, \"p\") #" }
    ],
    dataBound: function(e) {
      displayFilterResults();
    }
  });
});

The getData() method can be found here: https://gist.github.com/3159627

Example: paging demo.

Updates

  • 24/7/2012: Added a link to a demo

Telerik’s Kendo UI Grid

I’ve recently started to use Telerik’s Kendo UI framework for web applications and I have to say I’m very impressed. Although it does come with a bunch of server side extensions for ASP.NET MVC I’ve found that the javascript configuration to be just as easy.

Sample Data

For these posts I’ll be using various sample data. In this post, the data is visitor numbers to UK tourist attractions which I got from The Guardian.If you want to take the data and play with this sample, you can find the bva-data.js file as a gist on github.

I pulled the data into a .NET application and converted it to JSON. First I took the spreadsheet I downloaded and then saved it as CSV file. I brought it into my .NET application using a .NET CSV Reader I found on Code Project.

Grid configuration

$(function(){
  var data = getData(); // From the bva-data.js file
  $('#MyGrid').kendoGrid({
    dataSource: {
      data: data,
      schema: {
        model: {
          fields: {
            Site: {type: "string" },
            Visitors: {type: "number" },
            FreeCharge: {type: "string" },
            Change: {type: "number" }
          }
        }
      }
    },
    filterable: true,
    columnMenu: false,
    sortable: true,
    columns: [ 
      { field: "Site" }, 
      { field: "Visitors" }, 
      { field: "FreeCharge" }, ]
      { field: "Change", template: "#= kendo.toString(Change, \"p\") #" }
    ]
  });
});

First off, getData() is a simply loads the data so it is available in one array to start with. I didn’t want to complicate this with having lots of calls to other services.

The schema defines how the data is to be interpreted.

filterable defines if the grid columns can be filtered or not. How that filter is represented to user depends on whether columnMenu is true or false.

filterable : true

When filterable is set to true then an icon will appear in the right of the column header to indicate that you can apply a filter.

The filter allows you to specify one or two criteria for filtering the column.

Kendo UI Filterable Grid

Example: filterable demo.

schema

I’m not going to go too much into the schema at the moment. Suffice to say that it allows to to define how the grid interprets the data that has been sent to it.

In this example, I’m using the schema to define the type of each field in the data. That way the filtering options can interpret the data correctly. For example, the Visitors column is a number, so it would be better to give filter options such as “greater than” or “less than” instead of the default string filter options of “contains” or “starts with”. Like this:

Numeric filter on a Kendo UI Grid

Other data types that the schema.model can interpret are string (the default), boolean, and date.

columnMenu : true

By default, if you don’t specifiy a columnMenu, it will be false. and you won’t get the menu. If, however, you set columnMenu to true then there will be a small down-arrow displayed which when clicked displays the menu.

Without any other settings, the menu will just allow you to turn on and off columns. If you set sortable to true then you also get the “Sort Ascending” and “Sort Descending” options. And if you set filterable to true then you get a menu item for filtering the data as the menu item replaces the icon for filtering the data in the column header.

The image below shows the columnMenu with the sortable and filterable options turned on.

Kendo UI Grid Column Menu

Example: columnMenu demo.

template

In the definition of the Change column is a template parameter. This defines how the column should be displayed if it should not be simply displayed as is.

In this example, all that is happening is that the number is being represented as a percentage. The data contains the information as a floating point number so that a value of 0.05 is displayed as 5%.

Templated values are set between two # markers. After the opening marker you can put an equal sign or colon depending on how you want the value rendered. The = indicates the value is rendered as is, the : indicates that the value is to be HTML encoded before being rendered.

There is a toString function that allows you to format data in various ways. In this example, I’m taking a number and formatting it as a percentage. Like this:

#= kendo.toString(Change, "p") #

Just remember that if you have quotation marks inside your template to escape them if needs be for the code that the template is defined within.

Updates

  • 24/7/2012: Added links to demos.

JsRender and arrays

Previously, I showed how to very quickly get up and running with JsRender witha very simple hello world demonstation. In this post I’ll be extending things a little further showing you how simple arrays of data are handled.

For this demo I have an array of data representing photos from my flickr account. This is what the data looks like:

var thePhotos =
  [
    {
      "title":"Forth Road Bridge",
      "thumbnail":"http://farm1.staticflickr.com/1/2843652_f542c664ed_q.jpg",
      "url":"http://www.flickr.com/photos/colinangusmackay/2843652/in/photostream"
    }, {
      "title":"Forth Bridge",
      "thumbnail":"http://farm1.staticflickr.com/1/2843680_58c5c8003b_q.jpg",
      "url":"http://www.flickr.com/photos/colinangusmackay/2843680/in/photostream"
    }, {
      "title":"Helmsdale",
      "thumbnail":"http://farm1.staticflickr.com/4/5441773_2929a2ebdf_q.jpg",
      "url":"http://www.flickr.com/photos/colinangusmackay/5441773/in/photostream"
    }, {
      "title":"Scottish Parliament",
      "thumbnail":"http://farm1.staticflickr.com/3/6340272_0e7ad78251_q.jpg",
      "url":"http://www.flickr.com/photos/colinangusmackay/6340272/in/photostream"
    }, {
      "title":"Space Needle",
      "thumbnail":"http://farm3.staticflickr.com/2013/2410201132_356ff1a147_q.jpg",
      "url":"http://www.flickr.com/photos/colinangusmackay/2410201132/in/photostream"
    }
  ];

The template defines how to render a single element in the array. There is also a special token available {{:#index}} which allows you to get the index value into the template. In the example below, I’m adding one to it in order to put a sensible number next to the photo.

As you can also see, you can place template placeholders in many places, includeing inside attributes in HTML elements.

The template looks like this:

<script id="photosTemplate" type="text/x-jsrender">
  <div class="photoFrame">
    <span class="index">{{:#index+1}}</span>
    <a class="photoLink" href="{{:url}}">
      <span class="photoTitle">{{:title}}</span>
      <img class="photo" src="{{:thumbnail}}" alt="{{:title}}"/>
    </a>
  </div>
</script>

The code to render the template and add it to the page is pretty much the same as last time.

I’ve also put together a full example to look at, feel free to look at the source of this page.

JsRender …. starter for 10

I was going to look at jQuery Templates recently, but then I discovered they have been discontinued. Which is a real pity as I saw a demonstration at a conference about a year ago and they looked rather promising. However, there are other similar projects out there that do similar things. So instead, I’m going to look at JsRender and JsViews.

At the moment there is very little documenation out there for either JsRender or JsViews, so this is some of the bits I’ve been able to piece together. Some of the simpler demos actually only use JsRender. And, of course, at this stage the project is still pre-beta so some of this may change.

To get going you need to add a reference to the JsRender javascript library. You can find that on github. Although you don’t need jQuery for JsRender, it can take advantage of jQuery to make some things easier. I’ll be showing JsRender with jQuery as I happen to think it makes things easier.

Hello World!

To start with the template is rendered in a script block with a type of “text/x-jsrender”. The templated parts themselves are made up of two sets of braces with an expression inside. For example:

<script id="helloTemplate" type="text/x-jsrender">
  <p>Hello, {{:name}}!</p>
</script>

Next, we need some javascript to wire up the template with some data

<script type="text/javascript">
  $(function(){
    // Set up the data
    var thePerson = { name: "Colin" };

    // Render the template to a string
    var renderedHtml = $("#helloTemplate").render(thePerson);

    // insert the rendered template into an existing element
    // In this case it is a span.
    $("#container").html(renderedHtml);
  });
</script>

To see the example in action, click here and view the source of the page to see the underlying code.

Loading coffeescript unit tests from separate files

In my previous post I showed how to create unit tests for coffeescript. I also included a link to Eli Thompson’s coffeescript unit testing runner which allows you to easily gather all the .coffee files and the unit tests together in one place thus allowing you to keep your unit tests in separate files (rather than in-lining it in the test-runner as I showed in my previous example).

So far, so good. However, you cannot run this from the local file system as the browser’s security will complain (see the console panel in the screenshot below). The files are loaded using jQuery’s get method.

So, in order to get it to run you need to run it from within the context of a web server. You can use IIS if you are running windows, however for this example, I’m using Linux so I’ll use Apache.

Getting Apache up and running on Linux

To install Apache, in a terminal type:

sudo apt-get install apache2

By default, the newly installed server will serve from the /var/www/ which will contain an index.html already.

In order to create a new site that points to your development environment so that you can run the unit tests locally you need to modify apache.

Start by opening the /etc/apache2/apache2.conf file. (You’ll need to use sudo or run as root in order to write this back as your user won’t have the permission by default.) And add the following to the end of the file:

NameVirtualHost 127.0.0.1:80

This tells Apache that you’ll be creating named web sites on the IP/port specified. This is most useful if you have a server that hosts multiple sites. In our case we are simply using it to create a development site on our local machine. Because we’ve specified the loopback address it won’t be visible outside of the machine it is running on. (More info on NameVirtualHost)

Next we have to create a file in /etc/apache2/sites-available/ directory. As far as I can see, the convention is to use the host name as the name of the file. So a site running a www.example.com would have a file of the same name. In this case, as it is a development site running only on localhost I like to name it something along the lines of myproject-localhost so that it is obvious that it is running on the loop back address.

For this example, I’ll create a file called /etc/apache2/sites-available/coffee-tests-localhost with the following content:

<VirtualHost 127.0.0.1:80>
ServerName coffee-tests-localhost
ServerAlias www.coffee-tests-localhost
ServerAdmin colin.mackay@example.com
DocumentRoot /home/colinmackay/hg/blog-and-demos/three-of-a-kind
</VirtualHost>

Since this file is in sites-available that means it is not yet enabled, so the server won’t be serving it up. In order to get it served up there needs to be a duplicate in /etc/apache2/sites-enabled/. You don’t need to create a duplicate in Linux as you can create a symbolic link to the original file. To do that, type the following at a terminal:

cd /etc/apache2/sites-enabled/
sudo ln -s ../sites-available/coffee-tests-localhost .

(Note the dot at the end of the second line!)

Since the host name does not really exist, no DNS will resolve it, this is the point that you need to edit the /etc/hosts file so that your local browser can go to the web site. Add the following line to the hosts file:

127.0.0.1     coffee-tests-localhost

Finally restart the Apache server:

sudo /etc/init.d/apache2 restart

You should now have your web site up and running and displaying the tests to you now.

The running tests

When we go to http://coffee-tests-localhost/tests/test-runner.htmlall the tests now run and there is no error in the browser’s console:

More information