Bing Maps Sandboxed WebPart for SharePoint Online and SharePoint 2013

I wanted to create a simple Bing Maps Web Part for SharePoint 2013 Sandboxed solutions and for SharePoint Online.

This isn’t the same as my previous Map Web Part posts, however it isn’t too difficult. As before we just define a DIV element in our WebPart with an ID:

<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> 
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> 
<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%@ Import Namespace="Microsoft.SharePoint" %> 
<%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="FlightMapWebPart.ascx.cs" Inherits="AirTravel.FlightMapWebPart.FlightMapWebPart" %>
<div id='myMap' style="position:relative; width:600px; height:400px;"></div>

The the code behind is simple enough. The main point is just to get around the Sandbox security restrictions by writing out Javascript directly with RenderContents. I also added a property to set the Bing Maps key.

using System;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;

namespace AirTravel.FlightMapWebPart
{
    [ToolboxItemAttribute(false)]
    public partial class FlightMapWebPart : WebPart
    {
        /// <summary>
        /// Constructor
        /// </summary>
        public FlightMapWebPart()
        {
        }

        /// <summary>
        /// Set the Bing Maps Key with a WebPArt Property
        /// </summary>
        [WebBrowsable(true),
        WebDisplayName("Bing Maps Key"),
        WebDescription("Your Bing Map Key Value"),
        Personalizable(PersonalizationScope.Shared),
        Category("Bing Maps")]
        public string BingMapsKey { get; set; }

        /// <summary>
        /// On Initialize
        /// </summary>
        /// <param name="e"></param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            InitializeControl();
        }

        /// <summary>
        /// Create Child Controls
        /// </summary>
        protected override void CreateChildControls()
        {
            base.CreateChildControls();
        }

        /// <summary>
        /// On Page Load
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        /// <summary>
        /// Add addidional content to the webpart
        /// </summary>
        /// <param name="writer"></param>
        protected override void RenderContents(HtmlTextWriter writer)
        {
            base.RenderContents(writer);

            // Add reference to JQuery javascript
            writer.AddAttribute(HtmlTextWriterAttribute.Type, "text/javascript");
            writer.AddAttribute("language", "javascript");
            writer.AddAttribute(HtmlTextWriterAttribute.Src, "http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js");
            writer.RenderBeginTag(HtmlTextWriterTag.Script);
            writer.RenderEndTag();

            // Add reference to Bing Maps javascript
            writer.AddAttribute(HtmlTextWriterAttribute.Type, "text/javascript");
            writer.AddAttribute("language", "javascript");
            writer.AddAttribute(HtmlTextWriterAttribute.Src, "http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0");
            writer.RenderBeginTag(HtmlTextWriterTag.Script);
            writer.RenderEndTag();

            // Write javascript code
            writer.AddAttribute(HtmlTextWriterAttribute.Type, "text/javascript");
            writer.AddAttribute("language", "javascript");
            writer.RenderBeginTag(HtmlTextWriterTag.Script);
            writer.WriteLine(CreateLoadMapString(this.BingMapsKey));
            writer.WriteLine("LoadMap();");
            writer.RenderEndTag();
        }

        /// <summary>
        /// Create Load Map Javascript function
        /// </summary>
        /// <returns>Load Map Javascript String</returns>
        static private string CreateLoadMapString(string BingMapsKey)
        {
            // Sanitize, just in case some script passed instead of a key string
            string sanitized = HttpUtility.HtmlEncode(BingMapsKey);

            string mapDeclareString = "map = new Microsoft.Maps.Map(test, {credentials: '" + sanitized + "'});";

            StringBuilder js = new StringBuilder();
            js.AppendLine("var map = null;");
            js.AppendLine("function LoadMap() {");
            js.AppendLine("var test = document.getElementById('myMap');");
            js.AppendLine(mapDeclareString);
            js.AppendLine("}");

            return js.ToString();
        }


    }
}

And that’s it. Your WebPart can be used onpremise or on the cloud.
Image
One thing you may need to check is that the website where the Bing Maps Javascript file (LINK) resides is added to your Internet Explorer ‘Trusted Sites’ list.

Also of note is that waiting for the page to load with the JQuery ‘Ready’ function was not required before executing the Javascript.

UPDATE: I just noticed that I could pass a script through the webparts property! Added the HtmlEncode to make sure.

Advertisements

One thought on “Bing Maps Sandboxed WebPart for SharePoint Online and SharePoint 2013

  1. Excellent post – Do you know if Microsoft have removed the ability on Office 365 for code behind. I’ve simply created a visual web part (sandboxed) and it doesn’t seem to import. I’ve been using JSOM to overcome this issue but then I came across your post, which seems to suggest that they’ll allow this on O365. Custom JSOM webparts seem to import fine.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s