Infragistics jQuery Map Bookmarks in HTML5 Local Storage

[Infragistics] Mihail Mateev / Saturday, June 30, 2012

People often wants to keep a list of  favorite views (bookmarks) on their map.

This article describes how to implement persistence of the favorite views with the Infragistics jQuery Map using HTML5 Local Storage.

Local Storage

First lets start off with what localStorage is. Basically it is a client-side database. That is a database that resides in the users browser and not on your server. The difference between this database and others you may be familiar with resides in that this is for key-value storage. This means you won’t be writing some crazy SQL intense application while using localStorage.

We all know that browser support is important depending on your target audience with your app. In this case localStorage is supported by most modern browsers including Safari 4+, Mobile Safari (iPhone/iPad), Firefox 3.5+, Internet Explorer 10+ and Chrome 4+.

Where localStorage differs from cookies or sessionStorage is that the data stored in localStorage is still there even after the browser is closed and is shared across multiple windows. You don’t have to worry about a user deleting the cookies and all their data.

This is  a simple example of using localStorage

   1: localStorage.setItem("name", "Hello World!"); //saves to the database, key/value
   2: document.write(localStorage.getItem("name")); //Hello World!
   3: localStorage.removeItem("name"); //deletes the matching item from the database

Due to browser specific quotas you would want to check for exceptions

You might also want to check to see if the users browser even supports localStorage and if it doesn’t we can warn them. Now the code above would look like this:

   1: if (typeof(localStorage) == 'undefined' ) {
   2:     alert('Your browser does not support HTML5 localStorage. Try upgrading.');
   3: } else {
   4:     try {
   5:         localStorage.setItem("name", "Hello World!"); //saves to the database, "key", "value"
   6:     } catch (e) {
   7:           if (e == QUOTA_EXCEEDED_ERR) {
   8:                alert('Quota exceeded!'); //data wasn't successfully saved due to quota exceed so throw an error
   9:         }
  10:     }
  11:  
  12:     document.write(localStorage.getItem("name")); //Hello World!
  13:     localStorage.removeItem("name"); //deletes the matching item from the database
  14: }

 

Infragistics jQuery Map bookmarks – live demo

This sample is placed in JS FIDDLE (http://jsfiddle.net  ). Demo is available  here.

Before to start:

You need to refer NetAdvantage for jQuery scripts. The JavaScript files are available in a hosted environment on the Infragistics CDN.  The code below shows how to use it.

   1: 
   3:  
   4: 

 

JsFiddle

The sample in the JsFiddle is fully functional and you could change the source and see the results

Bookmarks

Map favorite views are stared in a JSON array of objects, represented map extends

   1: var bookmarks = getFromStorage("bookmarks");
   2: if(bookmarks == null)
   3: {
   4:     bookmarks=[];
   5: }

 

Map extend structure in JSON

   1: {"name": bookmarkName, "extent": {"left": currExtent.left, 
   2: "top": currExtent.top, "width": currExtent.width, 
   3: "height": currExtent.height }}

 

Storing Objects in HTML5 localStorage.
When you like to store a JavaScript object in HTML5 localStorage, your object is apparently being converted to a string.
A workaround can be to stringify your object before storing it, and later parse it when you retrieve it. You can use the same approach with igMap bookmarks

 

  • Read bookmarks from local storage
   1: //Get all bookmarks from storage
   2: function getFromStorage(key)
   3: {
   4:  
   5:     if (typeof(localStorage) == 'undefined' ) {
   6:         alert('Your browser does not support HTML5 localStorage. Try upgrading.');
   7:         return null;
   8:     } 
   9:     else {
  10:         try {
  11:  
  12:             var result = JSON.parse(localStorage.getItem(key));
  13:             return result;
  14:         } catch (e) {
  15:               if (e == QUOTA_EXCEEDED_ERR) {
  16:                    alert('Quota exceeded!'); //data wasn't successfully saved due to quota exceed so throw an error
  17:             }
  18:             return null;
  19:         }
  20:      
  21:     }
  22:  
  23: }

 

  • Save bookmarks in local storage
   1: //Save bookmarks in the storage
   2: function saveInStorage(key, value)
   3: {
   4:  
   5:     if (typeof(localStorage) == 'undefined' ) {
   6:         alert('Your browser does not support HTML5 localStorage. Try upgrading.');
   7:     } 
   8:     else {
   9:         try {
  10:             localStorage.setItem(key,JSON.stringify(value)); //saves to the database, "key", "value"
  11:         } catch (e) {
  12:               if (e == QUOTA_EXCEEDED_ERR) {
  13:                    alert('Quota exceeded!'); //data wasn't successfully saved due to quota exceed so throw an error
  14:             }
  15:         }
  16:      
  17:     }
  18:  
  19: }

 

UI implementation.

In the sample application are included igMap and igTree. Infragistics jQuery Tree is used to navigate between bookmarks when select the specified node from igTree.

  • Create a map instance
   1: $("#map").igMap({
   2:      width: "700px",
   3:      height: "500px",
   4:      panModifier: "control",
   5:      horizontalZoomable: true,
   6:      verticalZoomable: true,
   7:      windowResponse: "immediate",
   8:      overviewPlusDetailPaneVisibility: "visible",
   9:      seriesMouseLeftButtonUp: function(ui, args) {
  10:          var tets = args;
  11:      }
  12:  });
  13:  
  14:  $("#map").igMap("option", "windowRect", {
  15:      left: 0.27,
  16:      top: 0.20,
  17:      width: 0.5,
  18:      height: 0.5
  19:  });

 

  • Create an igTree instance
   1: $("#igTree").igTree({
   2:       height: 500, width: 220,
   3:      singleBranchExpand: false,
   4:          dataSourceType: 'json',
   5:          bindings: {
   6:          textKey: 'name',
   7:          valueKey: 'name',
   8:          childDataProperty: 'extent' 
   9:          },
  10:          dataSource: bookmarks
  11:      }); 
  12:  
  13:  $('#igTree').bind('igtreeselectionchanged', function (sender, eventArgs) {
  14:      var node = eventArgs.selectedNodes[0];
  15:      if(node != null)
  16:      {
  17:          $("#map").igMap("option", "windowRect", node.data.extent);
  18:      }
  19:      
  20:  });    

 

Add a new bookmark

To add a new bookmark you can get the igMap.windowRect current value an save it in a new object. After that the new extend should be added to the bookmarks array and the whole array is stored in the local storage.

   1: //Add a new bookmark
   2: function AddBookmark(){
   3:     var bookmarkName= $('#txtBookmarkName').val(); 
   4:     var currExtent = $("#map").igMap("option", "windowRect");
   5:     bookmarks.push({"name": bookmarkName, "extent": {"left": currExtent.left, "top": currExtent.top, "width": currExtent.width, "height": currExtent.height }}); 
   6:    
   7:       $("#igTree").igTree('option', 'dataSource', bookmarks); 
   8:       
   9:       saveInStorage("bookmarks", bookmarks);
  10:          
  11: }

 

Screens below show the steps when adding a bookmark

Delete the selected bookmark

To delete a bookmark you need to find the element from the bookmarks array, corresponding the selected igTree node, delete it and update data source of the Infragistics jQuery Tree.

   1: //Delete the selected bookmark
   2:    function DeleteBookmark()
   3:    {
   4:            var nodes = $("#igTree").igTree("selectedNode"); 
   5:            
   6:            var deleteNode = nodes.data;
   7:            
   8:            
   9:            
  10:            if(deleteNode  != null)
  11:            {
  12:                var index = parseInt(nodes.path);
  13:                bookmarks.splice(index , 1);
  14:                 $("#igTree").igTree('option', 'dataSource', bookmarks); 
  15:            }
  16:    }

  

Clear all bookmarks

To clear all bookmarks you just should set bookmarks to be an empty array and update igTree.dataSource option.

   1: //Clear all bookmarks
   2: function ClearBookmarks() {
   3:     bookmarks = [];
   4:     $("#igTree").igTree('option', 'dataSource', bookmarks); 
   5: }

Navigation between bookmarks with Infragistics jQuery Tree

When the igTree node is selected, the event handler sets the selected extend to the igMap.

   1: $('#igTree').bind('igtreeselectionchanged', function (sender, eventArgs) {
   2:     var node = eventArgs.selectedNodes[0];
   3:     if(node != null)
   4:     {
   5:         $("#map").igMap("option", "windowRect", node.data.extent);
   6:     }
   7:     
   8: });    

 

 

You can try the sample using Infragistics jQuery Map Bookmarks fiddle.

As always, you can follow us on Twitter: @mihailmateev and @Infragistics , all tweets with hashtag #infragistcs and stay in touch on Facebook, Google+ , LinkedIn and Infragistics Friends User Group !