User Tools

Site Tools


source_code_worldmapwmsservice_project_templates_web_cs.zip

Source Code WorldMapWmsService Project Templates Web CS.zip

SerializableFeature.cs

 using System.Collections.Generic;  
 using System.Runtime.Serialization;  
 using ThinkGeo.MapSuite.Core;  
 
 namespace ThinkGeo.MapSuite.WMSServiceClient  
 {  
     [DataContract]  
     public class SerializableFeature  
     {  
         private string id;  
         private string wkt;  
         private Feature feature;  
 
         [DataMember(Name|= "fieldValues")]  
         public Dictionary<string, string> fieldValues { get; set; }  
 
         [DataMember(Name|= "id")]  
         public string Id  
         {  
             get { return id; }  
             set { id = value; }  
         }  
 
         [DataMember(Name|= "wkt")]  
         public string Wkt  
         {  
             get { return wkt; }  
             set  
             {  
                 wkt = value;  
                 feature = new Feature(wkt);  
                 foreach (var fieldValue in fieldValues)  
                 {  
                     feature.ColumnValues.Add(fieldValue.Key, fieldValue.Value);  
                 }  
             }  
         }  
 
         public Feature RealFeature  
         {  
             get { return feature; }  
             set { feature = value; }  
         }  
 
     }  
 
     public class SerializableFeatures  
     {  
         private string name;  
 
         [DataMember(Name|= "name")]  
         public string Name  
         {  
             get { return name; }  
             set { name = value; }  
         }  
 
         [DataMember(Name|= "features")]  
         public SerializableFeature[] features { get; set; }  
     }  
 }  
 

User.cs

 
 namespace ThinkGeo.MapSuite.WMSServiceClient  
 {  
     public class User  
     {  
         private string userName;  
         private string clientId;  
         private string mapStyle;  
 
         public string UserName  
         {  
             get { return userName; }  
             set { userName = value; }  
         }  
 
         public string ClientId  
         {  
             get { return clientId; }  
             set { clientId = value; }  
         }  
 
         public string MapStyle  
         {  
             get { return mapStyle; }  
             set { mapStyle = value; }  
         }  
     }  
 }  
 

ready-functions.cs

 $(document).ready(function () {  
     window.onload = resizeElementHeight();  
     $(window).resize(resizeElementHeight);  
 
     $("#toggle").bind("click", function () {  
         if ($("#leftContainer").css("display") != "none") {  
             $("#toggleImage").attr("src", "../Images/expand.gif");  
             $("#map-content").css("width", "99%");  
             $("#toggle").css("left", "5px");  
             $("#leftContainer").css("display", "none");  
         }  
         else {  
             $("#leftContainer").css("display", "block");  
             $("#toggleImage").attr("src", "../Images/collapse.gif");  
             $("#map-content").css("width", "80%");  
             $("#toggle").css("left", "20%");  
         }  
         resizeElementHeight();  
     });  
 
     $("input[name='serviceArea']").change(function () {  
         if ($("#divService").is(':visible')) {  
             $("#divService").hide();  
             $("#divBuffer").show();  
         } else {  
             $("#divService").show();  
             $("#divBuffer").hide();  
         }  
     });  
 
     var btnTracks = $(this).find("input[type='image']");  
     for (var i = 0; i < btnTracks.length; i++) {  
         $(btnTracks[i]).bind("click", function () {  
             for (var i = 0; i < btnTracks.length; i++) {  
                 $(btnTracks[i]).css("border", "0px solid #D3D3D3");  
                 $(btnTracks[i]).css("background-color", "transparent");  
             }  
             $(this).css("border", "1px solid #D3D3D3");  
             $(this).css("background-color", "#eeeeee");  
         });  
     };  
 
     $("#dlgLoginRequired").dialog({  
         autoOpen: false,  
         modal: true,  
         buttons: {  
             Ok: function () {  
                 $("#btnNormal").trigger("click");  
                 $(this).dialog("close");  
             }  
         }  
     });  
 
     $("#btnDrawPoint").click(function () {  
         if ($("#lbxUsers").val() == "Anonymous") {  
             $("#dlgLoginRequired").dialog("open");  
             $(".ui-dialog-titlebar").hide();  
         }  
     });  
 
     $("#dlgErrorMessage").dialog({  
         autoOpen: false,  
         modal: true,  
         buttons: {  
             Ok: function () {  
                 $("#btnNormal").trigger("click");  
                 $(this).dialog("close");  
             }  
         }  
     });  
 });  
 
 var OnMapCreated = function (map) {  
     var map = webMap.GetOpenLayersMap();  
     map.events.register("mousemove", map, function (e) {  
         var mouseCoordinate = this.getLonLatFromPixel(new OpenLayers.Pixel(e.clientX, e.clientY));  
         if (mouseCoordinate) {  
             $("#coordinate").text("X:" + mouseCoordinate.lon.toFixed(6) + "  Y: " + mouseCoordinate.lat.toFixed(6));  
         }  
     });  
 }  
 
 function resizeElementHeight() {  
     var documentheight = $(window).height();  
     var contentDivH = documentheight - $("#footer").height() - $("#header").height() - 1;  
     $("#content-container").height(contentDivH + "px");  
 
     $("#leftContent").height(contentDivH + "px");  
     $("#map-content").height(contentDivH + "px");  
     $("#toggle").css("line-height", contentDivH + "px");  
 
     $("#mapContainer").height(contentDivH + "px");  
 
     // refresh the map.  
     webMap.GetOpenLayersMap().updateSize();  
 }  
 
 function pageLoad() {  
     resizeElementHeight();  
 }  
 
 
 

Default.aspx

 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ThinkGeo.MapSuite.WMSServiceClient.Default" %>  
 
 <%@ Register Assembly="WebEdition" Namespace="ThinkGeo.MapSuite.WebEdition" TagPrefix="cc1" %>  
 <!DOCTYPE html>  
 <html xml:en-us">  
 <head id="Head1" runat="server">  
     <title>World Map Wms Service Client</title>  
     <link href="Images/MapSuite.ico" rel="shortcut icon" type="Images/x-icon" />  
     <link href="Styles/jquery-ui-1.10.4.custom.min.css" rel="stylesheet" type="text/css" />  
     <link href="Styles/Site.css" rel="stylesheet" type="text/css" />  
     <script src="Scripts/jquery-1.10.2.js" type="text/javascript"></script>  
     <script src="Scripts/jquery-ui-1.10.4.custom.min.js" type="text/javascript"></script>  
 </head>  
 <body>  
     <form id="Form1" runat="server">  
         <asp:ScriptManager ID="ScriptManager1" runat="server">  
         </asp:ScriptManager>  
         <div id="container">  
             <div id="header">  
                 <div id="left-header">  
                     <span id="header-mapsuite">Map Suite</span> <span id="header-title">World Map Wms Service  
                     Client</span>  
                 </div>  
             </div>  
             <div id="content-container">  
                 <div id="leftContainer">  
                     <div id="leftContent">  
                         <h4>Access the WMS service as this user:  
                             <br />  
                             <span class="comments">("If you select "Anonymous", a watermark will be displayed and querying will be disabled) </span>  
                         </h4>  
                         <asp:UpdatePanel ID="UpdatePanel1" runat="server">  
                             <ContentTemplate>  
                                 <div class="divBorder">  
                                     <div class="divSettingItem">  
                                         <span class="title">User Name:</span>  
                                         <asp:DropDownList ID="ddlUsers" AutoPostBack="True" runat="server" OnSelectedIndexChanged="cbxUsers_OnSelectedIndexChanged">  
                                         </asp:DropDownList>  
                                     </div>  
                                     <div class="divSettingItem">  
                                         <span class="title">Wms Style:</span>  
                                         <input type="text" runat="server" id="txtStyle" disabled="disabled" />  
                                     </div>  
                                     <div class="divSettingItem">  
                                         <span class="title">Map Projection:</span>  
                                         <asp:DropDownList ID="ddlMapProjection" AutoPostBack="True" runat="server" OnSelectedIndexChanged="cbxMapProjection_OnSelectedIndexChanged">  
                                             <asp:ListItem Text="DecimalDegree"></asp:ListItem>  
                                             <asp:ListItem Text="Mercator"></asp:ListItem>  
                                         </asp:DropDownList>  
                                     </div>  
                                 </div>  
                             </ContentTemplate>  
                             <Triggers>  
                                 <asp:AsyncPostBackTrigger ControlID="ddlUsers" />  
                             </Triggers>  
                         </asp:UpdatePanel>  
                         <h4>Select the pin and click on the map to highlight the country you clicked:  
                         </h4>  
                         <div class="divBorder">  
                             <asp:ImageButton ID="btnNormal" runat="server" ToolTip="Pan the map"  
                                 ImageUrl="~/Images/pan.png" CommandArgument="PanMap" CssClass="active" OnCommand="OperateMapCommand" />  
                             <asp:ImageButton ID="btnDrawPoint" runat="server" ToolTip="Highlight a country"  
                                 ImageUrl="~/Images/drawPoint.png" CommandArgument="DrawPoint" OnCommand="OperateMapCommand" />  
                             <asp:ImageButton ID="btnClearAll" runat="server" ToolTip="Remove pin and selection"  
                                 CommandArgument="ClearAll" OnCommand="OperateMapCommand" ImageUrl="~/Images/clear.png" />  
                         </div>  
                         <div>  
                             <a href="http://localhost:52289/WmsHandler.axd?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetCapabilities"  
                                 target="_blank">Get WMS Capabilities</a>  
                         </div>  
                         <div>  
                             <a href="http://localhost:52289/Default.aspx"  
                                 target="_blank">View WMS Admin Page</a>  
                         </div>  
                     </div>  
                 </div>  
                 <div id="toggle">  
                     <img id="toggleImage" alt="collapse" src="Images/collapse.gif" />  
                 </div>  
                 <div id="map-content">  
                     <asp:UpdatePanel ID="mapContentPanel" runat="server" style="height: 100%;">  
                         <ContentTemplate>  
                             <cc1:Map ID="webMap" runat="server" Height="100%" Width="100%" OnTrackShapeFinished="WebMapOnTrackShapeFinished">  
                             </cc1:Map>  
                         </ContentTemplate>  
                         <Triggers>  
                             <asp:AsyncPostBackTrigger ControlID="btnNormal" />  
                             <asp:AsyncPostBackTrigger ControlID="btnDrawPoint" />  
                             <asp:AsyncPostBackTrigger ControlID="btnClearAll" />  
                             <asp:AsyncPostBackTrigger ControlID="ddlMapProjection" />  
                         </Triggers>  
                     </asp:UpdatePanel>  
                 </div>  
             </div>  
             <div id="footer">  
                 <span id="coordinate"></span>  
             </div>  
             <div id="dlgLoginRequired" title="Login Required">  
                 <p>  
                     Anonymous is not allowed to query the WMS service by clicking the map.  
                 </p>  
             </div>  
             <div id="dlgErrorMessage" title="Error Message">  
                 <p>  
                     No result found, please click on the continent to try again.  
                 </p>  
             </div>  
             <script type="text/javascript" src="Scripts/ready-functions.js"></script>  
         </div>  
     </form>  
 </body>  
 </html>  
 
 

Default.aspx.cs

 using System;  
 using System.Collections.ObjectModel;  
 using System.Globalization;  
 using System.IO;  
 using System.Linq;  
 using System.Net;  
 using System.Runtime.Serialization.Json;  
 using System.Text;  
 using System.Web;  
 using System.Web.UI;  
 using System.Web.UI.WebControls;  
 using System.Xml.Linq;  
 using System.Xml.XPath;  
 using ThinkGeo.MapSuite.Core;  
 using ThinkGeo.MapSuite.WebEdition;  
 
 namespace ThinkGeo.MapSuite.WMSServiceClient  
 {  
     public partial class Default : Page  
     {  
         private static readonly string serviceUri;  
         private static readonly string highlightKey;  
         private static readonly string markerOverlayKey;  
         private static readonly string srsDecimalDegree;  
         private static readonly string srsSphereMercator;  
         private static readonly string srsMapImageFormat;  
         private static readonly string srsFeatureFormat;  
         private static readonly Collection<User> users;  
 
         static Default()  
         {  
             highlightKey = "Highlight";  
             srsDecimalDegree = "EPSG:4326";  
             srsSphereMercator = "EPSG:900913";  
             markerOverlayKey = "Marker Overlay";  
             srsFeatureFormat = "TEXT/JSON";  
             srsMapImageFormat = "Png";  
             users = GetUsers();  
             serviceUri = "http://localhost:52289/WmsHandler.axd";  
         }  
 
         protected void Page_Load(object sender, EventArgs e)  
         {  
             if (!IsPostBack)  
             {  
                 // Initialize map.  
                 webMap.MapUnit = GeographyUnit.DecimalDegree;  
                 webMap.CurrentExtent = new RectangleShape(-170, 70, 170, -70);  
                 webMap.EditOverlay.TrackMode = TrackMode.None;  
 
                 InitializeOverlays();  
             }  
         }  
 
         protected void WebMapOnTrackShapeFinished(object sender, EventArgs e)  
         {  
             if (webMap.EditOverlay.Features.Count > 0)  
             {  
                 ClearAllShape();  
                 BaseShape shape = webMap.EditOverlay.Features[0].GetShape();  
                 webMap.EditOverlay.Features.Clear();  
 
                 PointShape centerPoint = shape as PointShape;  
                 if (centerPoint != null)  
                 {  
                     DisplayHighlightLayer(centerPoint);  
                     DisplayMarker(centerPoint);  
                     webMap.DynamicOverlay.Redraw();  
                 }  
             }  
         }  
 
         protected void OperateMapCommand(object sender, CommandEventArgs e)  
         {  
             switch (e.CommandArgument.ToString())  
             {  
                 case "DrawPoint":  
                     if (Session["ClientId"] == null)  
                     {  
                         ScriptManager.RegisterStartupScript(mapContentPanel, mapContentPanel.GetType(), " ", @"$('#dlgLoginRequired').dialog('open');$('.ui-dialog-titlebar').hide();", true);  
                     }  
                     else  
                     {  
                         webMap.EditOverlay.TrackMode = TrackMode.Point;  
                     }  
                     break;  
                 case "ClearAll":  
                     webMap.EditOverlay.TrackMode = TrackMode.None;  
                     ClearAllShape();  
                     break;  
                 default:  
                     webMap.EditOverlay.TrackMode = TrackMode.None;  
                     break;  
             }  
         }  
 
         protected void cbxUsers_OnSelectedIndexChanged(object sender, EventArgs e)  
         {  
             User currentUser = users[ddlUsers.SelectedIndex];  
 
             txtStyle.Value = currentUser.MapStyle;  
             Session["user"] = currentUser.UserName;  
             Session["ClientId"] = currentUser.ClientId;  
 
             WmsOverlay wmsOverlay = (WmsOverlay)webMap.CustomOverlays[0];  
             wmsOverlay.Parameters["ClientId"] = currentUser.ClientId;  
             wmsOverlay.Parameters["UserName"] = currentUser.UserName;  
         }  
 
         protected void cbxMapProjection_OnSelectedIndexChanged(object sender, EventArgs e)  
         {  
             ClearAllShape();  
             WmsOverlay wmsOverlay = (WmsOverlay)webMap.CustomOverlays[0];  
             if (ddlMapProjection.SelectedValue.Equals("DecimalDegree"))  
             {  
                 webMap.MapUnit = GeographyUnit.DecimalDegree;  
                 wmsOverlay.Parameters["srs"] = srsDecimalDegree;  
             }  
             else  
             {  
                 webMap.MapUnit = GeographyUnit.Meter;  
                 wmsOverlay.Parameters["srs"] = srsSphereMercator;  
             }  
         }  
 
         protected void cbxMapFormat_SelectedIndexChanged(object sender, EventArgs e)  
         {  
             WebImageFormat format = (WebImageFormat)Enum.Parse(typeof(WebImageFormat), srsMapImageFormat);  
             ((WmsOverlay)webMap.CustomOverlays[0]).WebImageFormat = format;  
         }  
 
         protected void cbxFeatureFormat_SelectedIndexChanged(object sender, EventArgs e)  
         {  
             ((WmsOverlay)webMap.CustomOverlays[0]).Parameters["INFO_FORMAT"] = srsFeatureFormat;  
         }  
 
         private void InitializeOverlays()  
         {  
             Uri uri = new Uri(serviceUri);  
             WmsOverlay wmsOverlay = new WmsOverlay("worldMapSerivce", uri);  
             wmsOverlay.Parameters.Add("layers", "WorldMap");  
             wmsOverlay.Parameters.Add("styles", "DEFAULT");  
             wmsOverlay.Parameters.Add("srs", srsDecimalDegree);  
             wmsOverlay.WebImageFormat = WebImageFormat.Png;  
             webMap.CustomOverlays.Add(wmsOverlay);  
 
             //Highlight layer.  
             InMemoryFeatureLayer highlightLayer = new InMemoryFeatureLayer();  
             GeoColor serviceAreaGeoColor = new GeoColor(120, GeoColor.FromHtml("#1749c9"));  
             highlightLayer.ZoomLevelSet.ZoomLevel01.DefaultAreaStyle = AreaStyles.CreateSimpleAreaStyle(serviceAreaGeoColor, GeoColor.SimpleColors.Yellow, 1, LineDashStyle.Solid);  
             highlightLayer.ZoomLevelSet.ZoomLevel01.ApplyUntilZoomLevel = ApplyUntilZoomLevel.Level20;  
             webMap.DynamicOverlay.Layers.Add(highlightKey, highlightLayer);  
 
             //Marker Overlay  
             SimpleMarkerOverlay markerOverlay = new SimpleMarkerOverlay(markerOverlayKey);  
             markerOverlay.IsVisibleInOverlaySwitcher = false;  
             webMap.CustomOverlays.Add(markerOverlay);  
 
             ddlUsers.DataSource = users;  
             ddlUsers.DataTextField = "UserName";  
             ddlUsers.DataBind();  
             txtStyle.Value = users[ddlUsers.SelectedIndex].MapStyle;  
         }  
 
         private void DisplayMarker(PointShape point)  
         {  
             InMemoryFeatureLayer highlightLayer = (InMemoryFeatureLayer)webMap.DynamicOverlay.Layers[highlightKey];  
             if (highlightLayer.InternalFeatures != null && highlightLayer.InternalFeatures.Count > 0)  
             {  
                 Feature currentFeature = highlightLayer.InternalFeatures.FirstOrDefault();  
 
                 Marker centerMarker = new Marker(point);  
                 centerMarker.Popup = new CustomPopup("CenterPoint", point, GetPopupContent(currentFeature));  
                 centerMarker.Popup.IsVisible = false;  
                 centerMarker.Popup.AutoSize = true;  
                 centerMarker.WebImage = new WebImage("/Images/drawPoint.png");  
                 centerMarker.WebImage.ImageOffsetX = -16;  
                 centerMarker.WebImage.ImageOffsetY = -16;  
 
                 // Add marker to overlay.  
                 SimpleMarkerOverlay markerOverlay = (SimpleMarkerOverlay)webMap.CustomOverlays[markerOverlayKey];  
                 markerOverlay.Markers.Add(centerMarker);  
             }  
         }  
 
         private void DisplayHighlightLayer(PointShape centerPoint)  
         {  
             Feature feature = QueryFeatureByPoint(centerPoint);  
 
             if (feature != null)  
             {  
                 InMemoryFeatureLayer highlightLayer = (InMemoryFeatureLayer)webMap.DynamicOverlay.Layers[highlightKey];  
 
                 highlightLayer.Open();  
                 highlightLayer.InternalFeatures.Clear();  
                 highlightLayer.InternalFeatures.Add(feature);  
                 webMap.CurrentExtent = highlightLayer.GetBoundingBox();  
             }  
         }  
 
         private Feature QueryFeatureByPoint(PointShape centerPoint)  
         {  
             // Construct the service request url.  
             string serviceUrl = GetQueryFeatureServiceUrl(centerPoint);  
 
             // Send request to server.  
             WebRequest getFeatureRequest = WebRequest.Create(serviceUrl);  
             WebResponse response = getFeatureRequest.GetResponse();  
 
             // Deserilize the feature from response.  
             DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(SerializableFeatures[]));  
             try  
             {  
                 Stream responseStream = response.GetResponseStream();  
                 if (responseStream != null)  
                 {  
                     SerializableFeatures[] features = (SerializableFeatures[])serializer.ReadObject(responseStream);  
                     if (features.Length == 0 || features.FirstOrDefault() == null)  
                         ShowErrorMessage();  
                     else  
                     {  
                         var responseFeature = features.FirstOrDefault();  
                         if (responseFeature != null)  
                         {  
                             var realFeature = responseFeature.features.FirstOrDefault();  
                             if (realFeature != null)  
                             {  
                                 return realFeature.RealFeature;  
                             }  
                         }  
                     }  
                 }  
             }  
             catch (Exception)  
             {  
                 ShowErrorMessage();  
             }  
             return null;  
         }  
 
         private string GetQueryFeatureServiceUrl(PointShape centerPoint)  
         {  
             ScreenPointF screenPoint = ExtentHelper.ToScreenCoordinate(webMap.CurrentExtent, centerPoint.X, centerPoint.Y, (float)webMap.WidthInPixels, (float)webMap.HeightInPixels);  
             string featureFormat = srsFeatureFormat;  
             string clientId = Session["ClientId"].ToString();  
             string mapFormat = srsMapImageFormat;  
             string projection = ddlMapProjection.SelectedValue.Equals("DecimalDegree") ? srsDecimalDegree : srsSphereMercator;  
             string bbox = ConvertBoundingBoxToString(webMap.CurrentExtent);  
 
             StringBuilder parameters = new StringBuilder();  
             parameters.Append(serviceUri + "?");  
             parameters.Append("LAYERS=WorldMap&");  
             parameters.Append("STYLES=DEFAULT&");  
             parameters.Append("SERVICE=WMS&");  
             parameters.Append("VERSION=1.1.1&");  
             parameters.Append("REQUEST=GETFEATUREINFO&");  
             parameters.Append("QUERY_LAYERS=WorldMap&");  
             parameters.AppendFormat(CultureInfo.InvariantCulture, "X={0}&", (int)screenPoint.X);  
             parameters.AppendFormat(CultureInfo.InvariantCulture, "Y={0}&", (int)screenPoint.Y);  
             parameters.AppendFormat(CultureInfo.InvariantCulture, "INFO_FORMAT={0}&", featureFormat);  
             parameters.AppendFormat(CultureInfo.InvariantCulture, "ClientId={0}&", clientId);  
             parameters.AppendFormat(CultureInfo.InvariantCulture, "FEATURE_COUNT={0}&", 1);  
             parameters.AppendFormat(CultureInfo.InvariantCulture, "FORMAT={0}&", mapFormat);  
             parameters.AppendFormat(CultureInfo.InvariantCulture, "SRS={0}&", projection);  
             parameters.AppendFormat(CultureInfo.InvariantCulture, "WIDTH={0}&", webMap.WidthInPixels);  
             parameters.AppendFormat(CultureInfo.InvariantCulture, "HEIGHT={0}&", webMap.HeightInPixels);  
             parameters.AppendFormat(CultureInfo.InvariantCulture, "BBOX={0}", bbox);  
             return parameters.ToString();  
         }  
 
         private void ShowErrorMessage()  
         {  
             ScriptManager.RegisterStartupScript(mapContentPanel, mapContentPanel.GetType(), " ", @"$('#dlgErrorMessage').dialog('open');$('.ui-dialog-titlebar').hide();", true);  
         }  
 
         private void ClearAllShape()  
         {  
             // Clear the highlight select layer.  
             InMemoryFeatureLayer hightLayer = (InMemoryFeatureLayer)webMap.DynamicOverlay.Layers[highlightKey];  
             hightLayer.InternalFeatures.Clear();  
 
             //Clear marker on marker.  
             SimpleMarkerOverlay markerOverlay = (SimpleMarkerOverlay)webMap.CustomOverlays[markerOverlayKey];  
             markerOverlay.Markers.Clear();  
 
             webMap.DynamicOverlay.Redraw();  
         }  
 
         private static string ConvertBoundingBoxToString(RectangleShape boundingBox)  
         {  
             return String.Format(CultureInfo.InvariantCulture, "{0},{1},{2},{3}", boundingBox.LowerLeftPoint.X, boundingBox.LowerLeftPoint.Y, boundingBox.UpperRightPoint.X, boundingBox.UpperRightPoint.Y);  
         }  
 
         private static string GetPopupContent(Feature feature)  
         {  
             string header = string.Empty;  
             string population = string.Empty;  
 
             if (feature.ColumnValues.ContainsKey("LONG_NAME"))  header = feature.ColumnValues["LONG_NAME"];  
             if (feature.ColumnValues.ContainsKey("POP_CNTRY")) population = feature.ColumnValues["POP_CNTRY"];  
 
             StringBuilder result = new StringBuilder();  
             result.AppendLine("<div width=200px>");  
             result.AppendLine("<strong> Name: " + header + "</strong>");  
             result.AppendLine("<div class='hrLine'></div>");  
             result.AppendLine("<font size='0.6px' color='gray'>");  
             result.AppendLine("Population: " + population + "
 ");  
             result.AppendLine("<font>");  
             result.AppendLine("</div>");  
 
             return result.ToString();  
         }  
 
         private static Collection<User> GetUsers()  
         {  
             Collection<User> result = new Collection<User>();  
             string userXmlPath = HttpContext.Current.Server.MapPath(@"~\UserDataXml\Users.xml");  
             XDocument xmlDocument = XDocument.Load(userXmlPath);  
             var usersInformation = xmlDocument.XPathSelectElements("Users/User");  
 
             foreach (var item in usersInformation)  
             {  
                 User user = new User();  
                 user.UserName = item.XPathSelectElement("UserName").Value;  
                 user.ClientId = item.XPathSelectElement("ClientId") == null ? string.Empty : item.XPathSelectElement("ClientId").Value;  
                 user.MapStyle = item.XPathSelectElement("MapStyle") == null ? string.Empty : item.XPathSelectElement("MapStyle").Value;  
                 result.Add(user);  
             }  
             return result;  
         }  
     }  
 }  
 
 

WorldMapPlugin.cs

 using System;  
 using System.Collections.Generic;  
 using System.Collections.ObjectModel;  
 using System.Drawing;  
 using System.IO;  
 using System.Linq;  
 using System.Runtime.Serialization.Json;  
 using System.Text;  
 using System.Web;  
 using ThinkGeo.MapSuite.Core;  
 using ThinkGeo.MapSuite.WmsServerEdition;  
 
 namespace ThinkGeo.MapSuite.WorldMapPlugins  
 {  
     public class WorldMapPlugin : WmsLayerPlugin  
     {  
         private const string SrsDecimalDegree = "EPSG:4326";  
         private const string SrsSphereMercator = "EPSG:900913";  
 
         public WorldMapPlugin()  
         {  
             BrowerCacheExpiration = TimeSpan.FromSeconds(0);  
             WmsQueryMode = WmsQueryMode.Queryable;  
         }  
 
         protected override string GetFeatureInfoCore(GetFeatureInfoRequest getFeatureInfoRequest, MapConfiguration cachedMapConfiguration,  
             HttpContext context)  
         {  
             bool userValidated = SecurityHelper.AuthenticateUserRequest(context);  
             string result = string.Empty;  
             if (userValidated)  
             {  
                 if (cachedMapConfiguration.Layers.Count != 0)  
                 {  
                     float pixelColumn = getFeatureInfoRequest.ScreenX;  
                     float pixelRow = getFeatureInfoRequest.ScreenY;  
                     PointShape interestPoint = ExtentHelper.ToWorldCoordinate(getFeatureInfoRequest.BoundingBox, new ScreenPointF(pixelColumn, pixelRow), getFeatureInfoRequest.Width, getFeatureInfoRequest.Height);  
                     foreach (Layer layer in cachedMapConfiguration.Layers)  
                     {  
                         FeatureLayer featureLayer = layer as FeatureLayer;  
                         if (featureLayer != null)  
                         {  
                             layer.Open();  
                             Collection<Feature> nearestFeatures =  
                                 featureLayer.QueryTools.GetFeaturesContaining(interestPoint,  
                                     ReturningColumnsType.AllColumns);  
                             layer.Close();  
 
                             if (nearestFeatures.Any())  
                             {  
                                 string featureString = base.GetFeatureInfoCore(getFeatureInfoRequest,  
                                     cachedMapConfiguration, context);  
                                 result = JsonFormatter.PrettyPrint(featureString);  
                             }  
                         }  
                     }  
                 }  
             }  
             else  
             {  
                 result = "Failed Authentication";  
             }  
 
             return result;  
         }  
 
         protected override Bitmap GetMapCore(GetMapRequest getMapRequest, MapConfiguration mapConfiguration, HttpContext context)  
         {  
             string imageFormat = context.Request.QueryString["Format"];  
             string userName = context.Request.QueryString["UserName"];  
 
             BackgroundLayer backgroundLayer = mapConfiguration.Layers["Background"] as BackgroundLayer;  
             if (backgroundLayer != null) backgroundLayer.BackgroundBrush = new GeoSolidBrush(GeoColor.FromArgb(255, 153, 179, 204));  
 
             Bitmap mapImage = null;  
             bool userValidated = SecurityHelper.AuthenticateUserRequest(context);  
             ShapeFileFeatureLayer layer = mapConfiguration.Layers["WorldLayer"] as ShapeFileFeatureLayer;  
             if (layer != null)  
             {  
                 layer.ZoomLevelSet.ZoomLevel01.DefaultAreaStyle = GetAreaStyleByUserName(userName, userValidated);  
                 mapImage = base.GetMapCore(getMapRequest, mapConfiguration, context);  
             }  
 
             if (!userValidated)  
             {  
                 mapImage = mapImage ?? base.GetMapCore(getMapRequest, mapConfiguration, context);  
                 PointShape centerPoint = getMapRequest.BoundingBox.GetCenterPoint();  
                 GdiPlusGeoCanvas canvas = new GdiPlusGeoCanvas();  
                 canvas.BeginDrawing(mapImage, getMapRequest.BoundingBox, GetGeographyUnit(getMapRequest.Crs));  
                 canvas.DrawTextWithWorldCoordinate("Your watermark here", new GeoFont("Arial", 11, DrawingFontStyles.Bold), new GeoSolidBrush(new GeoColor(100, GeoColor.StandardColors.Purple)), centerPoint.X, centerPoint.Y, DrawingLevel.LevelOne);  
                 canvas.EndDrawing();  
             }  
 
             return mapImage;  
         }  
 
         protected override RectangleShape GetBoundingBoxCore(string crs)  
         {  
             RectangleShape extent = new RectangleShape(-131.22, 55.05, -54.03, 16.91);  
             if (crs.Equals(SrsSphereMercator, StringComparison.OrdinalIgnoreCase))  
             {  
                 extent = new RectangleShape(-7635821.32160111, 14783156.7095771, 12088600.9533321, -14783156.7095771);  
             }  
             return extent;  
         }  
 
         protected override MapConfiguration GetMapConfigurationCore(string style, string crs)  
         {  
             MapConfiguration mapConfiguration = new MapConfiguration();  
 
             BackgroundLayer backgroundLayer = new BackgroundLayer(new GeoSolidBrush(GeoColor.SimpleColors.White));  
             mapConfiguration.Layers.Add("Background", backgroundLayer);  
 
             // Get the directory to the sample data  
 
             string worldLayerFilePath = Path.Combine(Directory.GetParent(Directory.GetParent(AppDomain.CurrentDomain.BaseDirectory).FullName).FullName, "SampleData", "Countries02.shp");  
 
             // Create the world layer from a shapefile and add a style to it  
             ShapeFileFeatureLayer worldLayer = new ShapeFileFeatureLayer(worldLayerFilePath);  
             worldLayer.ZoomLevelSet.ZoomLevel01.DefaultAreaStyle = AreaStyles.Country1;  
             worldLayer.ZoomLevelSet.ZoomLevel01.ApplyUntilZoomLevel = ApplyUntilZoomLevel.Level20;  
 
             WorldMapKitLayer worldMapKit = new WorldMapKitLayer();  
             worldMapKit.Projection = WorldMapKitProjection.DecimalDegrees;  
 
             switch (crs)  
             {  
                 case SrsSphereMercator:  
                     Proj4Projection proj4 = new Proj4Projection();  
                     proj4.InternalProjectionParametersString = Proj4Projection.GetDecimalDegreesParametersString();  
                     proj4.ExternalProjectionParametersString = Proj4Projection.GetSphericalMercatorParametersString();  
                     worldLayer.FeatureSource.Projection = proj4;  
                     break;  
             }  
 
             // Create a MapConfiguration and add the layer to it  
             mapConfiguration.Layers.Add("WorldLayer", worldLayer);  
 
             return mapConfiguration;  
         }  
 
         protected override string GetNameCore()  
         {  
             return "WorldMap";  
         }  
 
         protected override Collection<string> GetProjectionsCore()  
         {  
             return new Collection<string> { SrsDecimalDegree, SrsSphereMercator };  
         }  
 
         protected override GeographyUnit GetGeographyUnitCore(string crs)  
         {  
             GeographyUnit geographyUnit = GeographyUnit.DecimalDegree;  
             switch (crs)  
             {  
                 case SrsSphereMercator:  
                     geographyUnit = GeographyUnit.Meter;  
                     break;  
             }  
             return geographyUnit;  
         }  
 
         protected override Collection<WmsLayerStyle> GetStylesCore()  
         {  
             Collection<WmsLayerStyle> styles = new Collection<WmsLayerStyle>();  
             styles.Add(new WmsLayerStyle("DEFAULT"));  
             styles.Add(new WmsLayerStyle("Style1"));  
             styles.Add(new WmsLayerStyle("Style2"));  
 
             return styles;  
         }  
 
         private static AreaStyle GetAreaStyleByUserName(string userName, bool userValidated)  
         {  
             if (!userValidated) return AreaStyles.NoData1;  
 
             AreaStyle areaStyle = AreaStyles.Country1;  
             switch (userName)  
             {  
                 case "User2":  
                     areaStyle.OutlinePen.Color = GeoColor.StandardColors.Black;  
                     break;  
 
                 case "User3":  
                     areaStyle.FillSolidBrush.Color = GeoColor.StandardColors.White;  
                     break;  
 
                 default:  
                     areaStyle = AreaStyles.NoData1;  
                     break;  
             }  
 
             return areaStyle;  
         }  
 
         internal static string ConvertFeaturesToJson(Feature feature)  
         {  
             Collection<SerializableFeature> jsonFeatures = new Collection<SerializableFeature>();  
 
             Dictionary<string, string> jsonFields = new Dictionary<string, string>();  
             foreach (string fieldKey in feature.ColumnValues.Keys)  
             {  
                 jsonFields.Add(fieldKey, feature.ColumnValues[fieldKey]);  
             }  
 
             jsonFeatures.Add(new SerializableFeature(feature.Id, feature.GetWellKnownText(), jsonFields));  
 
 
             return JsonConvertor.ConvertObjectToStringUsingWcf(jsonFeatures);  
         }  
     }  
 }  
 
 internal class JsonConvertor  
 {  
     private JsonConvertor()  
     { }  
 
     public static string ConvertObjectToStringUsingWcf(object jsonObject)  
     {  
         string resultString;  
 
         DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(jsonObject.GetType());  
         MemoryStream jsonStream = null;  
         try  
         {  
             jsonStream = new MemoryStream();  
             jsonSerializer.WriteObject(jsonStream, jsonObject);  
             resultString = Encoding.UTF8.GetString(jsonStream.GetBuffer());  
             return resultString.Trim('\0');  
         }  
         finally  
         {  
             if (jsonStream != null) { jsonStream.Dispose(); }  
         }  
     }  
 }  
 
source_code_worldmapwmsservice_project_templates_web_cs.zip.txt · Last modified: 2015/09/09 03:38 by admin