Saturday, September 21, 2013

How to use REST to integrate SharePoint 2010 list data with jVectorMap

jVectorMap Series 
How to Build a Simple jVectorMap Display
How to integrate data with jVectorMap
How to customize jVectorMap region popups
How to add user interactivity to jVectorMap
How to add a popup modal to jVectorMap using Bootstrap
How to integrate jVectorMap with SharePoint 2010
How to use REST to integrate SharePoint 2010 list data with jVectorMap
How to use SOAP to integrate SharePoint 2010 list data with jVectorMap
Introduction

In the previous posting of this series, we explored how to migrate jVectorMap to the SharePoint 2010 platform.  In this posting, we will explore how to use REST to integrate SharePoint 2010 list data with jVectorMap.  The integration path involves: a SharePoint 2010 list, SharePoint 2010 REST services, jQuery, JSON, and jVectorMap.  By adding just a few lines of script to what has been developed thus far, we can extract list data into a JSON array and then pass this array into the series.region.values object in order to implement region coloration.   Building this integration path involves the following steps:
  1. Create the data list
  2. Identify REST svc URL
  3. Add data to the list
  4. Develop the script
  5. Test
The integration path presented here tested successfully using jQuery version 1.9.0. It did not test successfully with version 1.9.1.  Other versions have not yet been tested.

Step 1: Create the data list
  1. In SharePoint 2010, create a new list. Name the list without using spaces or non-CHARs so as to avoid HTML parsing changes. For this posting, the list is called CountryData. Leave the name of the Title field default. This field will contain the country digraph.
  2. Add a new field. Name the field without using spaces or non-CHARs in the name to avoid internal name conversion changes. For this posting, the new field is named Data.
Step 2: Identify REST service URL
  1. Open a browser, and then navigate to the site.
  2. Append the following to this URL: _vti_bin/listdata.svc, and then navigate to this URL
  3. Review the lists available via the REST interface. Append to the URL the name of the desired list. Note the capitalization.
  4. Append to this URL the querystring for selecting just the necessary fields from this list (note that meta information is still pulled even though its field, __metadata, (that's two underscores)is not specifically included):
    ?$select=Title,Data
  5. For this posting, the final URL is the following:
    ...[yoursite]/_vti_bin/ListData.svc/CountryData()?$select=Title,Data
    
Step 3: Add data to the list
  1. Add data to this list. For this posting, the same data used in previous postings is used for this one
  2. Open a browser and navigate to the URL obtained in the previous step. All of the list rows will appear:
Step 4: Develop the script
  1. First, modify the general jQuery function call so that script is executed after the DOM is ready. Change:
    (function () {
    
    to
    $(document).ready(function () {
    
  2. Define a variable for the REST service URL, and then enclose the script developed previously in a getJSON function
    var qryWCFUrl = "...yoursite/_vti_bin/ListData.svc/CountryData()?$select=Title,Data";
    $.getJSON(qryWCFUrl, function (results) {
    .
    .
    .
    });
    
  3. Add the script that:
    1. extracts the appropriate fields from the REST results,
    2. builds a key/value string from these results,
    3. parses the string into JSON format and
    4. loads it into an array.
    var mycdata;
    var myString = "{";
    $.each(results.d.results, function (i, item) {
     myString = myString + '"' + item.Title + '":"' + item.Data + '",';
    });
    myString = myString + '"ZZ":"1"}';
    mycdata = JSON.parse(myString);
    
  4. Change the variable used previously to pass data into the map, cdata, to the new variable, or mycdata, as used in this posting. Change:
    values: cdata
    to
    values: mycdata
  5. Optional: Add a click event handler that presents a popup of the stringified JSON data:
    $('#get-data').click(function(){
     alert(JSON.stringify(mycdata));
    });
  6. Optional: Add a button that the event handler binds to.
    <input id="get-data" name="Button4" type="button" value="Get Data" />
Step 5: Test
  1. Open a browser to the new page.  The results will appear identical
  2. Click on the new function button to see the stringified JSON data array
Final Script

Below is the final script that includes all of the modifications discussed above:

<script type="text/javascript" >    function showHelpDialog(){      var options = {        title: "jVectorMap help",        width: 400,        height: 600,        url: "helpDialog.aspx" };       SP.UI.ModalDialog.showModalDialog(options);    };    $(document).ready(function () {       var qryWCFUrl = "http://spdev12:4000/jVectorMap/_vti_bin/ListData.svc/CountryData()?$select=Title,Data"    $.getJSON(qryWCFUrl, function (results) {          var mycdata;     var myString = "{";     $.each(results.d.results, function (i, item) {      myString = myString + '"' + item.Title + '":"' + item.Data + '",';     });     myString = myString.substring(0, myString.length-1) + '}';     mycdata = JSON.parse(myString);        function chkValue(val){         if (typeof val ==="undefined"){           x = 0;         }         else{           x = val;          }         return x;       };              $('#focus-single').click(function(){          $('.map1').vectorMap('set', 'focus', 'SE');        });            //Reset focus        $('#focus-init').click(function(){          $('.map1').vectorMap('set', 'focus', 1, 0, 0);        });            //Clears all region colors        $('#clear-map').click(function(){        var map = $('.map1').vectorMap('get', 'mapObject');        map.series.regions[0].clear();        });            $('#get-data').click(function(){       alert(JSON.stringify(mycdata));     });       $('.map1').vectorMap({           map: 'world_mill_en',       //Set the initial focus to the center of the map       //at the maximum zoom out           focusOn: {             x: 0.5,             y: 0.5,             scale: 1           },       series: {            //this is the object for passing country/region data into        regions: [{               //define the range of color values         scale: ['#DEEBF7', '#08519C'],         //define the function that maps data to color range              normalizeFunction: 'linear',         //define the coloration method               attribute: 'fill',         //define the array of country data               values: mycdata             }]           },           onRegionLabelShow: function(event, label, code){            label.html('<img src="/jVectorMap/CountryFlags/' +             code.toString() + '.png" /> ' + label.html() +             '<hr noshade="noshade" style="height: 1px"/>Count: ' +             chkValue(cdata[code]));           }        }); //closes jVectorMap      }); //closes JSON      }) //closes jQuery function  </script>

Summary

In this posting, we have explored a simple method for extracting data from a SharePoint 2010 list,  and then ingesting this into the jVectorMap series.region object.  This integration path employed jQuery, JSON and REST services. Using this simple integration path, data in a SharePoint 2010 list can be used to support jVectorMap region coloration.  This method may also be used to support more complex integration, such as supporting region popups, marker placement and configuration and other solutions.

References
Notes
  • SharePoint Server 2010 Standard or Enterprise?  Either works for this.
  • REST vs. SOAP: the integration path presented here is much  simpler than that which would be necessary using SOAP methods.

No comments: