HTML5 Geolocation & Canvas Custom Controls Demo

View this Demo on your Mobile Device!

The first thing you will want to do is Allow the JavaScript that's currently attempting to access your current location.

Mind you, there are errors that I throw to the browser console (or firebug lite) when you deny the attempt to use the Geolocation methods, but the demo really demands that you allow it.

The html5:geolocation Custom Control creates two Client Side JavaScript global variables -- based on the Custom Property values you've set when you setup the Custom Control -- as well as builds the getLocation() function.



The above example generates the following Client Side JavaScript:

<script type="text/javascript">
var myLatitude;
var myLongitude;
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(setVars, printError);
    else {
        console.log('Geolocation is not supported by this browser.');
function setVars(position) {
    myLatitude = position.coords.latitude;
    myLongitude = position.coords.longitude;
function printError(error) {
    switch(error.code) {
        case error.PERMISSION_DENIED:
        console.log('User denied the request for Geolocation.');
      console.log('Location information is unavailable.');
    case error.TIMEOUT:
      console.log('The request to get user location timed out.');
    case error.UNKNOWN_ERROR:
      console.log('An unknown error occurred.');

This gives us two global variables that will be populated with the latitude and longitude information, error handling writing out to the browser console, and all we really need to do to kick this into motion is to call the getLocation() function

Step 1: getLocation Button

Step 2: mapIt() with HTML5 Canvas

The html5:canvas Custom Control is designed to create a simple HTML5 <canvas> element.



The above example generates the following HTML markup:


Now, we'll use this HTML5 canvas to paint a Google Static Maps API-based map image of our current location.

mapIt() function:

function mapIt() {
    document.getElementById('latitude').value = myLatitude;
    document.getElementById('longitude').value = myLongitude;
    if(confirm('Click OK to map it!')) {
        var canvas = document.getElementById('map');
        var context = canvas.getContext('2d');
        var imgObj = new Image();
        imgObj.onload = function() {
            context.drawImage(imgObj, 0, 0);
        imgObj.src = '' + myLatitude + ',' + myLongitude + '&sensor=false';

The mapIt() function will be used to set the value of two UI fields, and then paint the HTML5 canvas with the map image returned from the Google Static Maps API which is built using our myLatitude and myLongitude JavaScript Global Variables.