现在的位置: 首页 > 综合 > 正文

Sharepoint学习笔记—Site Definition系列–9、如何在Site Definition中整合Bing Map

2012年01月01日 ⁄ 综合 ⁄ 共 17191字 ⁄ 字号 评论关闭

  这里我们将会在Site Definition中创建一个Visual Web Part,然后在这个Web Part中呈递出Bing Map的内容。所以涉及的内容如下
   1、在Site Definition中引入Web Part

   2、在Site Definition中引入User Control

   3、在Site Definition中添加对 Bing 地图服务的引用(Web Services)

   4、在Default页面上引用 Web Part

   实践本文的前提是你需要创建一个Bing Map账户,创建帐户请点击此处

   然后通过Bing Maps账户管理中心创建Key,使用Windows Live ID登录账户管理中心就可以完成创建,每个Live ID可以创建5个开发Key。

   有了开发Key接着来就可以进行基于Bing Maps相关的功能开发了。 这些Key的用途在于让Bing Map来鉴别你的应用程序。更多BingMap的内容请参考

   这里直接进入我们的操作步骤,我们将基于Sharepoint学习笔记—Site Definition系列--如何在Site Definition中引入Master Page (2、Css等资源的引入)的项目来继续我们的开发,所以本文不再另建项目。

   首先,我们需要在此项目中引入Visual Web Part。这个Visual Web Part还包含另一个用户控件,此用户控件用于导航操控我们的地图。
   所以请先在项目中新添加一个Visual Web Part,命名为BingMapWebPart,如下图:

  
   点击Add按钮后系统会给我们自动创建好Visual Web Part的框架,

   并且还会新添加一个Feature名为Feature2,把我们的BingMapWebPart放到这个Feature2中:

  

  我们先不管新增控件的代码,先继续加入所需的其它内容,这里再添加一个用户自定义控件BingMapNav.ascx ,它提供了导航按钮以便于我们对地图进行zoom in/out, pane left/right/top/bottom等操作。
  添加方法是先给项目Map一个ControlTemplates目录,再在这个目录下添加一个名为BingMapNav.ascx (下面示意图中是BingMapNavNew,但这里请使用BingMapNav命名) 的用户控件。

 

 

  
  接下来我们要引入Bing Map的Service,方法是选中项目,点击鼠标右键,在弹出菜单中选择Add Service Reference,如下图

   在设置窗口输入如下地址
  http://dev.virtualearth.net/webservices/v1/geocodeservice/geocodeservice.svc?wsdl
 并作如下设置

 

  点击确定,照上面同样的方法添加
http://dev.virtualearth.net/webservices/v1/imageryservice/imageryservice.svc?wsdl
  并命名在NameSpace栏输入ImageryService。

  添加了对WebService的引用后,我们需要添加一个类BingMapHelper,这个类的作用是提供调用Bing Map Service的方法。BingMapHelper.cs 的代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySiteDefinitionTest.GeoCodeService;
using MySiteDefinitionTest.ImageryService;

namespace MySiteDefinitionTest
{
    class BingMapHelper
    {
        // static string key = "You bing map key here";
        static string key = "Your Bing Map Key";
        #region Helper Methods
        public static GeocodeResponse GeocodeAddressGeocodeResponse(string address)
        {
            GeocodeRequest geocodeRequest = new GeocodeRequest();

            // Set the credentials using a valid Bing Maps key
            geocodeRequest.Credentials = new MySiteDefinitionTest.GeoCodeService.Credentials();
            geocodeRequest.Credentials.ApplicationId = key;

            // Set the full address query
            geocodeRequest.Query = address;

            // Set the options to only return high confidence results 
            ConfidenceFilter[] filters = new ConfidenceFilter[1];
            filters[0] = new ConfidenceFilter();
            filters[0].MinimumConfidence = MySiteDefinitionTest.GeoCodeService.Confidence.High;

            // Add the filters to the options
            GeocodeOptions geocodeOptions = new GeocodeOptions();
            geocodeOptions.Filters = filters;
            geocodeRequest.Options = geocodeOptions;

            // Make the geocode request
            GeocodeServiceClient geocodeService = new GeocodeServiceClient("BasicHttpBinding_IGeocodeService");
            GeocodeResponse geocodeResponse = geocodeService.Geocode(geocodeRequest);
            return geocodeResponse;
        }

        public static string GetImagery(double latitude, double longititude, int zoom)
        {
            MapUriRequest mapUriRequest = new MapUriRequest();

            // Set credentials using a valid Bing Maps key
            mapUriRequest.Credentials = new MySiteDefinitionTest.ImageryService.Credentials();
            mapUriRequest.Credentials.ApplicationId = key;

            // Set the location of the requested image
            mapUriRequest.Center = new MySiteDefinitionTest.ImageryService.Location();

            mapUriRequest.Center.Latitude = latitude;
            mapUriRequest.Center.Longitude = longititude;

            // Set the map style and zoom level
            MapUriOptions mapUriOptions = new MapUriOptions();
            mapUriOptions.Style = MapStyle.AerialWithLabels;
            mapUriOptions.ZoomLevel = zoom;

            // Set the size of the requested image in pixels
            mapUriOptions.ImageSize = new MySiteDefinitionTest.ImageryService.SizeOfint();
            mapUriOptions.ImageSize.Height = 400;
            mapUriOptions.ImageSize.Width = 500;

            mapUriRequest.Options = mapUriOptions;

            //Make the request and return the URI
            ImageryServiceClient imageryService = new ImageryServiceClient("BasicHttpBinding_IImageryService");
            MapUriResponse mapUriResponse = imageryService.GetMapUri(mapUriRequest);
            return mapUriResponse.Uri;
        }
        #endregion Helper Methods
    }
}

    此时我们的项目如下图:

   

    接下来我们要回到前面创建的创建的Visual Web Part与 User Control来修改其相应的代码。
    首先是UserControl的代码
    BingMapNav.ascx界面定义代码如下:

<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%@ Import Namespace="Microsoft.SharePoint" %> 
<%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="BingMapNav.ascx.cs" Inherits="MySiteDefinitionTest.ControlTemplates.BingMapNav" %>
<table>
    <tr>
        <td colspan="2">Zoom
        </td>
        <td>
            <asp:button runat="server" text="^" ID="btnUp" onclick="btnUp_Click" />
        </td>
        <td>
            <asp:button runat="server" text="&gt;" ID="btnRight" onclick="btnRight_Click" />
        </td>
    </tr>
    <tr>
        <td>
            <asp:button runat="server" text="-" ID="btnZoomOut" 
                onclick
="btnZoomOut_Click" />
        </td>
        <td>
            <asp:button runat="server" text="+" ID="btnZoomIn" onclick="btnZoomIn_Click" />
        </td>
        <td>
            <asp:button runat="server" text="v" ID="btnDown" onclick="btnDown_Click" />
        </td>
        <td>
            <asp:button runat="server" text="&lt;" ID="btnLeft" onclick="btnLeft_Click" />
        </td>
    </tr>
    
</table>

   BingMapNav.ascx.cs代码内容如下

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

namespace MySiteDefinitionTest.ControlTemplates
{
    public partial class BingMapNav : UserControl
    {
        public event ButtonClickDelegate ZoomInButtonClick;
        public event ButtonClickDelegate ZoomOutButtonClick;
        public event ButtonClickDelegate ScrollUpButtonClick;
        public event ButtonClickDelegate ScrollDownButtonClick;
        public event ButtonClickDelegate ScrollLeftButtonClick;
        public event ButtonClickDelegate ScrollRightButtonClick;

        public delegate void ButtonClickDelegate();
        public string Raj;

        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void btnZoomOut_Click(object sender, EventArgs e)
        {
            if (ZoomOutButtonClick != null)
            {
                ZoomOutButtonClick();
            }
            else
            {
                throw new Exception("Nav:ZoomOut event not registered");
            }
        }

        protected void btnZoomIn_Click(object sender, EventArgs e)
        {
            if (ZoomInButtonClick != null)
            {
                ZoomInButtonClick();
            }
        }

        protected void btnUp_Click(object sender, EventArgs e)
        {
            if (ScrollUpButtonClick != null)
            {
                ScrollUpButtonClick();
            }
        }

        protected void btnDown_Click(object sender, EventArgs e)
        {
            if (ScrollDownButtonClick != null)
            {
                ScrollDownButtonClick();
            }
        }

        protected void btnRight_Click(object sender, EventArgs e)
        {
            if (ScrollRightButtonClick != null)
            {
                ScrollRightButtonClick();
            }
        }

        protected void btnLeft_Click(object sender, EventArgs e)
        {
            if (ScrollLeftButtonClick != null)
            {
                ScrollLeftButtonClick();
            }
        }
    
    }
}

   然后我们再来定义Visual Web Part的相关代码
   BingMapWebPartUserControl.ascx界面代码定义如下

<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls"
    Assembly
="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Register TagPrefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages"
    Assembly
="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="BingMapWebPartUserControl.ascx.cs"
    Inherits
="MySiteDefinitionTest.BingMapWebPart.BingMapWebPartUserControl" %>
<%@ Register Src="~/_controltemplates/BingMapNav.ascx" TagName="BingMapNav" TagPrefix="uc1" %>

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        <div>
            <table width="100%" style="height: 500px">
                <tr style="height: 30px" valign="top">
                    <td align="center" height="30px">
                        Enter address
                        <asp:TextBox runat="server" ID="txtAddress" ValidationGroup="BingMapsWP" Width="300px">3600 One Microsoft Way Redmond 98052</asp:TextBox>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtAddress"
                            ErrorMessage
="* Required" ValidationGroup="BingMapsWP"></asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr style="height: 40px" valign="top">
                    <td align="center" height="30px">
                        <asp:Button ID="btnGetMap" runat="server" Text="Get Maps" ValidationGroup="BingMapsWP"
                            OnClick
="btnGetMap_Click" />
                        <br />
                        <asp:Label ID="lblError" runat="server" Text="Label"></asp:Label>
                    </td>
                </tr>
                <tr>
                    <td align="center">
                        <asp:Image runat="server" ID="mapImage" Visible="False"></asp:Image>
                    </td>
                </tr>
                <tr style="height: 30px">
                    <td align="center">
                        <uc1:BingMapNav ID="BingMapNav1" runat="server" />
                    </td>
                </tr>
            </table>
        </div>
    </ContentTemplate>
</asp:UpdatePanel>

  
 上面代码中,此段代码

<%@ Register Src="~/_controltemplates/BingMapNav.ascx" TagName="BingMapNav" TagPrefix="uc1" %>

 的作用是在我们的Visual Web Part中引入我们定义的用户自定义控件BingMapNav。

 

 BingMapWebPartUserControl.ascx.cs代码如下:

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

using MySiteDefinitionTest.GeoCodeService;
using MySiteDefinitionTest.ImageryService;
using MySiteDefinitionTest.ControlTemplates;

namespace MySiteDefinitionTest.BingMapWebPart
{
    public partial class BingMapWebPartUserControl : UserControl
    {
        const string longititudeKey = "longititude";
        const string latitudeKey = "latitude";
        const string zoomKey = "zoom";

        double longititude;
        double latitude;
        int zoom = 15;

        protected void Page_Load(object sender, EventArgs e)
        {
            lblError.Visible = true;
            if (ViewState[longititudeKey] != null)
            {
                longititude = (double)ViewState[longititudeKey];
                latitude = (double)ViewState[latitudeKey];
                zoom = (int)ViewState[zoomKey];
            }

            //if (!Page.IsPostBack)
            {
                ((BingMapNav)BingMapNav1).ZoomOutButtonClick += new BingMapNav.ButtonClickDelegate(ZoomOut);
                ((BingMapNav)BingMapNav1).ZoomInButtonClick += new BingMapNav.ButtonClickDelegate(ZoomIn);
                ((BingMapNav)BingMapNav1).ScrollDownButtonClick += new BingMapNav.ButtonClickDelegate(ScrollDown);
                ((BingMapNav)BingMapNav1).ScrollLeftButtonClick += new BingMapNav.ButtonClickDelegate(ScrollLeft);
                ((BingMapNav)BingMapNav1).ScrollRightButtonClick += new BingMapNav.ButtonClickDelegate(ScrollRight);
                ((BingMapNav)BingMapNav1).ScrollUpButtonClick += new BingMapNav.ButtonClickDelegate(ScrollUp);
            }
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            ViewState[longititudeKey] = longititude;
            ViewState[latitudeKey] = latitude;
            ViewState[zoomKey] = zoom;
        }

        protected void ZoomOut()
        {
            zoom -= 2;
            lblError.Text = "New Zoom " + zoom;
            mapImage.ImageUrl = MySiteDefinitionTest.BingMapHelper.GetImagery(latitude, longititude, zoom);
        }

        protected void ZoomIn()
        {
            zoom += 2;
            lblError.Text = "New Zoom " + zoom;
            mapImage.ImageUrl = BingMapHelper.GetImagery(latitude, longititude, zoom);
        }

        protected void ScrollDown()
        {
            latitude -= 0.2;
            lblError.Text = "New latitude " + latitude;
            mapImage.ImageUrl = BingMapHelper.GetImagery(latitude, longititude, zoom);
        }

        protected void ScrollLeft()
        {
            longititude -= 0.2;
            lblError.Text = "New longititude " + longititude;
            mapImage.ImageUrl = BingMapHelper.GetImagery(latitude, longititude, zoom);
        }

        protected void ScrollRight()
        {
            longititude += 0.2;
            lblError.Text = "New longititude " + longititude;
            mapImage.ImageUrl = BingMapHelper.GetImagery(latitude, longititude, zoom);
        }

        protected void ScrollUp()
        {
            latitude += 0.2;
            lblError.Text = "New latitude " + latitude;
            mapImage.ImageUrl = BingMapHelper.GetImagery(latitude, longititude, zoom);
        }

        protected void btnGetMap_Click(object sender, EventArgs e)
        {
            lblError.Visible = false;
            try
            {
                //Get map

                GeocodeResponse resp = BingMapHelper.GeocodeAddressGeocodeResponse(txtAddress.Text);
                latitude = resp.Results[0].Locations[0].Latitude;
                longititude = resp.Results[0].Locations[0].Longitude;

                //Get URI and set image
                mapImage.ImageUrl = BingMapHelper.GetImagery(latitude, longititude, zoom);

                //Show image
                mapImage.Visible = true;
            }
            catch (Exception ex)
            {
                lblError.Visible = true;
                lblError.Text = ex.Message + "<BR>" + ex.StackTrace;
            }
        }
    }
}

 作完了上述工作后,任务还没结束,我们还需要修改app.config文件以配合Web Service的使用。因此请打开项目内的app.config文件,找到标识的内容并删除 decompressionEnable="true"

app.config的代码内容如下:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="BasicHttpBinding_IGeocodeService" closeTimeout="00:01:00"
                    openTimeout
="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                    allowCookies
="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
                    maxBufferSize
="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                    messageEncoding
="Text" textEncoding="utf-8" transferMode="Buffered"
                    useDefaultWebProxy
="true">
                    <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                        maxBytesPerRead
="4096" maxNameTableCharCount="16384" />
                    <security mode="None">
                        <transport clientCredentialType="None" proxyCredentialType="None"
                            realm
="" />
                        <message clientCredentialType="UserName" algorithmSuite="Default" />
                    </security>
                </binding>

                <binding name="BasicHttpBinding_IImageryService" closeTimeout="00:01:00"
                    openTimeout
="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                    allowCookies
="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
                    maxBufferSize
="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
          

抱歉!评论已关闭.