Slides

This weekend i was delighted to present a new session on the SharePoint Geolocation field.  It was a great interactive session with lots of input, comments and suggestions from the audience.

There are a great many uses for the geolocation field and we are getting more and more used to adding location information to our content to get additional dynamics on our data.

This session runs you through the requirements to enable the Geolocation field in your environments (with the code to do so) and also runs through setting up the field on a list, adding data and viewing the Map information.

Using SharePoint's Geolocation Field - SPSUK 2014 from Mark Stokes

Sample Code

During my session I used a "test harness" that contained the code for:

  1. Setting and retrieving the Bing Maps key on an SPWeb
  2. Adding the Geolocation Field to a list
  3. Importing CSV data to a list
This code is adapted /extended from a blog post i found by a guy called Borislav Grgić and the original source can be found here. This code has a reliance on JQuery, you know where to get that from! and also JQuery CSV.
<script src="/sites/geo/Style%20Library/Javascript/jquery-1.11.1.min.js"></script>
<script src="/sites/geo/Style Library/Javascript/jquery.csv-0.71.min.js"></script>

<script type="text/javascript">
var clientContext;
var relativeAdress;
var crimeDataUrl = "https://xxxxxxxxx.sharepoint.com/sites/geo/Shared%20Documents/2014-09-greater-manchester-street.csv";
var UKTownsDataUrl = "https://xxxxxxxxx.sharepoint.com/sites/geo/Shared%20Documents/UK%20Towns.csv";

function AddGeolocationField() {
    ClearNotifications();
    GetRelativeAdress();
    clientContext = new SP.ClientContext(relativeAdress);

    var web = clientContext.get_web();
    var targetList = web.get_lists().getByTitle(document.getElementById('listname_input_id').value);
    var fields = targetList.get_fields();

    fields.addFieldAsXml(
                "<Field Type='Geolocation' DisplayName='" + document.getElementById('fieldname_input_id').value + "'/>",
                true,
                SP.AddFieldOptions.addToDefaultContentType);

    clientContext.load(fields);
    clientContext.executeQueryAsync(function (sender, args) {
        document.getElementById('success_id').innerHTML = "You have succesfully created new geolocation field.";
    },
    function (sender, args) {
        document.getElementById('error_id').innerHTML = "Error: "+args.get_message();
    });
}


function SetBingKey() {
    ClearNotifications();
    GetRelativeAdress();
    clientContext = new SP.ClientContext(relativeAdress);

    var web = clientContext.get_web();
    var webProperties = web.get_allProperties();

    webProperties.set_item("BING_MAPS_KEY", document.getElementById('bing_key_id').value);
    web.update();

    clientContext.load(web);

    clientContext.executeQueryAsync(function (sender, args) {
        document.getElementById('success_id').innerHTML = "You have succesfully entered BING map key on "+web.get_title()+" site";
    }, function (sender, args) {
        document.getElementById('error_id').innerHTML = "Error: "+args.get_message();
    });
}

function GetBingKey() {

    ClearNotifications();
    GetRelativeAdress();
    clientContext = new SP.ClientContext(relativeAdress);

    var web = clientContext.get_web();

    var webProperties = web.get_allProperties();
    clientContext.load(webProperties);

    clientContext.executeQueryAsync(function (sender, args) {
        document.getElementById('bing_key_id').value = (webProperties.get_fieldValues()["BING_MAPS_KEY"]);

    }, function (sender, args) {
        document.getElementById('bing_key_id').value = "";
        document.getElementById('error_id').innerHTML = "Property not found! Please check your web site relative URL.";
    });
}

function importCSV() {
    ClearNotifications();

    var csvUrl = document.getElementById('csvurl_input_id').value;

    $.ajax({
        url: csvUrl,
        async: false,
        success: function (csvd) {
            var data = $.csv2Array(csvd);

            processArray(data);
        },
        dataType: "text",
        complete: function () {
            // call a function on complete
            //alert('Done');
        },
        error: function () {
            alert('data load error.');
        }
    });
}

var itemAddedCount = 0;
var itemErrorCount = 0;

function processArray(data) {
    GetRelativeAdress();
    clientContext = new SP.ClientContext(relativeAdress);

    var web = clientContext.get_web();
    var oList = web.get_lists().getByTitle(document.getElementById('listname_input_id').value);

    var geolocationFieldName = document.getElementById('fieldname_input_id').value;
    var latitudeFieldName = document.getElementById('latitudefieldname_input_id').value;
    var longitudeFieldName = document.getElementById('longitudefieldname_input_id').value;

    var  columnHeaders = data[0].toString().split(",");

    for(var i=1; i < data.length-1; i++) {
        // get the columns for each textline
        var dataColumns = data[i].toString().split(",");
        var longitudeValue = "";
        var latitudeValue = "";

        var itemCreateInfo = new SP.ListItemCreationInformation();
        this.oListItem = oList.addItem(itemCreateInfo);

        // loop over all columns and fill the corresponding fields of the listitem
        for (var x=0; x < dataColumns.length; x++)
        {
            if(x < columnHeaders.length && columnHeaders[x] != '')
            {
                if(columnHeaders[x] === latitudeFieldName) {
                    latitudeValue = dataColumns[x];
                } else if (columnHeaders[x] === longitudeFieldName) {
                    longitudeValue = dataColumns[x];
                } else {
                    if(dataColumns[x])
                        this.oListItem.set_item(columnHeaders[x], dataColumns[x]);
                }
            }
        }

        // Setup the Geolocation field. "POINT ([long] [Lat])"
        var locationFieldValue = "POINT (" + longitudeValue + " " + latitudeValue + ")"
        this.oListItem.set_item(geolocationFieldName, locationFieldValue);

        this.oListItem.update();
        clientContext.load(this.oListItem);

        clientContext.executeQueryAsync(
                Function.createDelegate(this, this.onListItemAddedSucceeded),
                Function.createDelegate(this, this.onListItemAddedFailed)
        );
    }
}

function onListItemAddedSucceeded(sender, args) {
    itemAddedCount = itemAddedCount + 1;
    document.getElementById('success_id').innerHTML = 'You have succesfully added item: ' + itemAddedCount;
}

function onListItemAddedFailed(sender, args) {
    itemErrorCount = itemErrorCount + 1;
    document.getElementById('error_id').innerHTML = 'Items not added. ' + itemErrorCount;
}

function ClearNotifications(){
    document.getElementById('success_id').innerHTML = "";
    document.getElementById('error_id').innerHTML = "";
    itemAddedCount = 0;
    itemErrorCount = 0;
}

function GetRelativeAdress(){
  if (document.getElementById('webrelative_url_id').value === "")
            relativeAdress = "/";
        else
            relativeAdress = document.getElementById('webrelative_url_id').value;
  if(relativeAdress.charAt(0)!='/')
     document.getElementById('error_id').innerHTML = "Relative adress has to start with /";
}

function crimeData() {
    document.getElementById('listname_input_id').value = "Manchester - 2014-09";
    document.getElementById('fieldname_input_id').value = "Location";
    document.getElementById('csvurl_input_id').value = crimeDataUrl;
}

function townsData() {
    document.getElementById('listname_input_id').value = "UK Towns";
    document.getElementById('fieldname_input_id').value = "Position";
    document.getElementById('csvurl_input_id').value = UKTownsDataUrl;
}

</script>

<table style="width: 480px;">
    <tbody>
<tr>
        <td style="width: 200px;">Web relative URL:</td>
        <td style="width: 5px;">&nbsp</td>
        <td valign="top">
            <input id="webrelative_url_id" name="relative" type="text" value="/sites/geo">
            <label style="font-size: 8pt;">* Input web relative URL and select "Get BING key" to check if key is set</label>
        </td>
        <td style="text-align: right;" valign="top">
            <input onclick="GetBingKey()" type="button" value="Get BING key">
        </td>
    </tr>
<tr>
        <td style="width: 200px;" valign="top">Bing Maps Key:</td>
        <td style="width: 5px;">&nbsp</td>
        <td valign="top">
            <input id="bing_key_id" name="bingkey" type="text">
            <label style="font-size: 8pt;">* Input Bing map key and relative url to web site to wich you wish to add the key</label>
        </td>
        <td style="text-align: right;" valign="top"><input onclick="SetBingKey()" type="button" value="Set BING key">
        </td>


    </tr>
<tr>
        <td style="width: 200px;" valign="top">List name:</td>
        <td style="width: 5px;">&nbsp</td>
        <td valign="top">
            <input id="listname_input_id" name="listname" type="text">
            <label style="font-size: 8pt;">* Name of the list where you wish to add your new geolocation field</label>
        </td>
        <td></td>
    </tr>
<tr>
        <td valign="top">Field name:</td>
        <td style="width: 5px;">&nbsp</td>
        <td valign="top">
            <input id="fieldname_input_id" name="fieldname" type="text">
            <label style="font-size: 8pt;">* Name of the new geolocation field you wish to add</label>
        </td>
        <td style="text-align: right;" valign="top">
            <input onclick="AddGeolocationField()" type="button" value="Create field">
        </td>
    </tr>
<tr>
        <td valign="top">Longitude CSV Field name:</td>
        <td style="width: 5px;">&nbsp</td>
        <td valign="top">
            <input id="longitudefieldname_input_id" name="longitudefieldname" type="text" value="Longitude">
            <label style="font-size: 8pt;">* Name of the csv field to use for longitude</label>
        </td>
        <td style="text-align: right;" valign="top"></td>
    </tr>
<tr>
        <td valign="top">Latitude CSV Field name:</td>
        <td style="width: 5px;">&nbsp</td>
        <td valign="top">
            <input id="latitudefieldname_input_id" name="latitudefieldname" type="text" value="Latitude">
            <label style="font-size: 8pt;">* Name of the csv field to use for latitude</label>
        </td>
        <td style="text-align: right;" valign="top"></td>
    </tr>
<tr>
        <td style="width: 200px;" valign="top">CSV File Url:</td>
        <td style="width: 5px;"> </td>
        <td valign="top">
            <input id="csvurl_input_id" name="csvurl" type="text" value="">
            <label style="font-size: 8pt;">* Input relative url to the csv file you would like to import to the list.</label>
        </td>
        <td style="text-align: right;" valign="top">
            <input onclick="importCSV()" type="button" value="Import CSV data">
        </td>
    </tr>
</tbody></table>

<div>
    Pre-load: <a href="javascript: return false;" onClick="crimeData();">Crime Data</a> |
              <a href="javascript: return false;" onClick="townsData();">UK Towns</a>
</div>

<div>
    <label id="error_id" style="color: red;"></label>
    <label id="success_id" style="color: green;"></label>
</div>
Mark Stokes [MVP]