ThinkGeo Cloud
ThinkGeo UI Controls
ThinkGeo Open Source
Help and Support
External Resources
ThinkGeo Cloud
ThinkGeo UI Controls
ThinkGeo Open Source
Help and Support
External Resources
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ThinkGeo.MapSuite.USDemographicMap._Default" %> <%@ Register Assembly="WebEdition" Namespace="ThinkGeo.MapSuite.WebEdition" TagPrefix="cc1" %> <!DOCTYPE html> <html xml:en-us"> <head id="Head1" runat="server"> <title>US Demographic Map</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="IE=Edge"> <link href="Images/MapSuite.ico" rel="shortcut icon" type="Images/x-icon" /> <link href="Styles/jquery-ui-1.10.4.custom.css" rel="stylesheet" type="text/css" /> <link href="Styles/bootstrap.min.css" rel="stylesheet" type="text/css" /> <link href="Styles/bootstrap-colorselector.css" rel="stylesheet" type="text/css" /> <link href="Styles/Site.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="Scripts/modernizr-2.5.3.js"></script> <script src="Scripts/jquery-1.10.2.js" type="text/javascript"></script> <script src="Scripts/jquery-ui-1.10.4.custom.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">US Demographic Map</span> </div> </div> <div id="content-container"> <div id="leftContainer"> <div id="leftContent"> <h4> Select data for display:</h4> <div id="accordion"> <asp:Repeater ID="rptCategoryList" runat="server" OnItemDataBound="rptCategoryList_ItemDataBound"> <ItemTemplate> <h3> <img alt="Population" src='<%#Eval("CategoryImage") %>' /> <asp:Label ID="lbTitle" runat="server" CssClass="accordion-header" Text='<%#Eval("Title")%>'></asp:Label> <input type="image" class="accordion-header-right" alt="Pie" title="Chart Map" src="Images/pie.png" style="visibility: hidden;" /> </h3> <div> <ul> <asp:Repeater ID="rptSubCategoryList" runat="server"> <ItemTemplate> <li><span class="accordion-content"> <%#Eval("Alias") %></span> <input id="ckbSelected" class="accordion-content-right" type="checkbox" checked="checked" style="visibility: hidden; margin: 8px 10px 0 0;" /> <img class="accordion-content-right" alt="DotDensity" title="Present the data with Dot Density." src="Images/DotDensity.png" /> <img class="accordion-content-right" alt="Thematic" title="Present the data in Thematic Colors." src="Images/Thematic.png" /> <img class="accordion-content-right" alt="ValueCircle" title="Present the data in Value Circles." src="Images/ValueCircle.png" /> </ItemTemplate> </asp:Repeater> </ul> </div> </ItemTemplate> </asp:Repeater> </div> <div class="settings"> <div class="settings"> <span id="spanBaseColor" class="settingTitle">Display Start Color:</span> <select id="colorStartselector"> </select> </div> <div id="divEndColor" class="settings"> <span class="settingTitle">Display End Color:</span> <select id="colorEndselector"> </select> </div> <div id="divColorWheel" class="settings"> <span class="settingTitle">ColorWheelDirection:</span> <select id="slColorWheelDirection" class="settingItem"> <option value="Clockwise">Clockwise</option> <option value="CounterClockwise" selected="selected">CounterClockwise</option> </select> </div> </div> <div id="divSlider" class="settings"> <span id="spanSliderTitle" class="settingTitle"></span> <div id="slider" class="settingItem"> </div> </div> <input type="hidden" id="clientStatusKeeper" value="" /> </div> </div> <div id="toggle"> <img alt="collapse" src="Images/collapse.gif" /> </div> <div id="map-content"> <cc1:Map ID="Map1" runat="server" Height="100%" Width="100%"> </cc1:Map> </div> </div> <div id="footer"> <span id="spanMouseCoordinate"></span> </div> </div> <script type="text/javascript" src="Scripts/bootstrap.min.js"></script> <script src="Scripts/bootstrap-colorselector.js" type="text/javascript"></script> <script type="text/javascript" src="Scripts/ready-functions.js"></script> </form> </body> </html>
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Configuration; using System.Globalization; using System.Linq; using System.Text; using System.Web.UI; using System.Web.UI.WebControls; using System.Xml.Linq; using ThinkGeo.MapSuite.Core; using ThinkGeo.MapSuite.WebEdition; namespace ThinkGeo.MapSuite.USDemographicMap { public partial class _Default : System.Web.UI.Page, ICallbackEventHandler { private static Dictionary<string, Category> categories; private string callbackResult; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { InitializeMapControl(); categories = LoadCategories(); rptCategoryList.DataSource = categories.Values; rptCategoryList.DataBind(); Page.ClientScript.GetCallbackEventReference(this, "", "", ""); } } public string GetCallbackResult() { return callbackResult; } public void RaiseCallbackEvent(string eventArgument) { // Replace the "$=" with ">=", because the ">=" is not allowed in AJAX Content if (eventArgument.Contains("$")) { eventArgument = eventArgument.Replace("$", ">="); } JsonCallbackRequest callbackRequest = JSONSerializer.Deserialize<JsonCallbackRequest>(eventArgument); switch (callbackRequest.Request.ToLowerInvariant()) { case "applystyle": callbackResult = UpdateMapAndLegend(callbackRequest).ToString(); break; case "identify": callbackResult = GetIdentifiedFeatureInfo(callbackRequest); break; default: break; } } private string GetIdentifiedFeatureInfo(JsonCallbackRequest callbackRequest) { // Get the requested sub-categories Category selectedCategory = null; Collection<CategoryItem> selectedCategoryItems = new Collection<CategoryItem>(); if (callbackRequest.StyleBuildType == DemographicStyleBuilderType.PieChart) { selectedCategoryItems = GetCategoryItemByAlias(callbackRequest.SelectedCategoryItems, ref selectedCategory); } else { selectedCategoryItems = GetCategoryItemByAlias(new Collection<string>() { callbackRequest.RequestColumnAlias }, ref selectedCategory); } // Get the selected columns Collection<string> selectedColumns = new Collection<string>(); foreach (CategoryItem categoryItem in selectedCategoryItems) { selectedColumns.Add(categoryItem.ColumnName); } selectedColumns.Add("Name"); // Find the identified feature with specified columns ShapeFileFeatureLayer statesLayer = Map1.DynamicOverlay.Layers["usStatesLayer"] as ShapeFileFeatureLayer; statesLayer.Open(); Feature identifiedFeature = statesLayer.FeatureSource.GetFeatureById(callbackRequest.SelectedFeatureId, selectedColumns); // Format the inner-html of the popup StringBuilder popupHtml = new StringBuilder("<table>"); popupHtml.Append(string.Format("<tr><td class='popupTitle'>{0}</td></tr>", identifiedFeature.ColumnValues["Name"])); popupHtml.Append("<tr><td><div class='hrLine'></div></td></tr>"); for (int i = 0; i < selectedColumns.Count - 1; i++) { string formatedString = DemographicStyleTextFormatter.GetFormatedString(selectedColumns[i], double.Parse(identifiedFeature.ColumnValues[selectedColumns[i])); popupHtml.Append(string.Format("<tr class='popupText'><td>{0}</td></tr>", formatedString)); } popupHtml.Append("</table>"); return popupHtml.ToString(); } private bool UpdateMapAndLegend(JsonCallbackRequest callbackRequest) { // Get the requested sub-categories Category selectedCategory = null; Collection<CategoryItem> selectedCategoryItems = new Collection<CategoryItem>(); if (callbackRequest.StyleBuildType == DemographicStyleBuilderType.PieChart) { selectedCategoryItems = GetCategoryItemByAlias(callbackRequest.SelectedCategoryItems, ref selectedCategory); } else { selectedCategoryItems = GetCategoryItemByAlias(new Collection<string>() { callbackRequest.RequestColumnAlias }, ref selectedCategory); } DemographicStyleBuilder demographicStyle = null; switch (callbackRequest.StyleBuildType) { case DemographicStyleBuilderType.PieChart: demographicStyle = new PieChartDemographicStyleBuilder(); foreach (CategoryItem categoryItem in selectedCategoryItems) { ((PieChartDemographicStyleBuilder)demographicStyle).SelectedColumnAliases.Add(categoryItem.Alias); } if (!string.IsNullOrEmpty(callbackRequest.StartColor)) { ((PieChartDemographicStyleBuilder)demographicStyle).Color = GeoColor.FromHtml(callbackRequest.StartColor); } break; case DemographicStyleBuilderType.Thematic: demographicStyle = new ThematicDemographicStyleBuilder(); if (!string.IsNullOrEmpty(callbackRequest.StartColor)) { ((ThematicDemographicStyleBuilder)demographicStyle).StartColor = GeoColor.FromHtml(callbackRequest.StartColor); } if (!string.IsNullOrEmpty(callbackRequest.EndColor)) { ((ThematicDemographicStyleBuilder)demographicStyle).EndColor = GeoColor.FromHtml(callbackRequest.EndColor); } if (!string.IsNullOrEmpty(callbackRequest.ColorWheelDirection)) { ((ThematicDemographicStyleBuilder)demographicStyle).ColorWheelDirection = callbackRequest.ColorWheelDirection.Equals("Clockwise") ? ColorWheelDirection.Clockwise : ColorWheelDirection.CounterClockwise; } break; case DemographicStyleBuilderType.DotDensity: demographicStyle = new DotDensityDemographicStyleBuilder(); if (!string.IsNullOrEmpty(callbackRequest.StartColor)) { ((DotDensityDemographicStyleBuilder)demographicStyle).Color = GeoColor.FromHtml(callbackRequest.StartColor); } if (callbackRequest.SliderValue > 0) { ((DotDensityDemographicStyleBuilder)demographicStyle).DotDensityValue = 50 * (callbackRequest.SliderValue / 3.0); } break; case DemographicStyleBuilderType.ValueCircle: demographicStyle = new ValueCircleDemographicStyleBuilder(); if (!string.IsNullOrEmpty(callbackRequest.StartColor)) { ((ValueCircleDemographicStyleBuilder)demographicStyle).Color = GeoColor.FromHtml(callbackRequest.StartColor); } if (callbackRequest.SliderValue > 0) { ((ValueCircleDemographicStyleBuilder)demographicStyle).RadiusRatio = callbackRequest.SliderValue / 3.0; } break; default: break; } foreach (CategoryItem categoryItem in selectedCategoryItems) { demographicStyle.SelectedColumns.Add(categoryItem.ColumnName); } ShapeFileFeatureLayer statesLayer = Map1.DynamicOverlay.Layers["usStatesLayer"] as ShapeFileFeatureLayer; statesLayer.ZoomLevelSet.ZoomLevel01.CustomStyles.Clear(); ThinkGeo.MapSuite.Core.Style selectedStyle = demographicStyle.GetStyle(statesLayer.FeatureSource); statesLayer.ZoomLevelSet.ZoomLevel01.CustomStyles.Add(selectedStyle); statesLayer.ZoomLevelSet.ZoomLevel01.ApplyUntilZoomLevel = ApplyUntilZoomLevel.Level20; Map1.DynamicOverlay.Redraw(); // update the legend based on the selected style UpdateLegend(demographicStyle); return true; } protected void rptCategoryList_ItemDataBound(object sender, RepeaterItemEventArgs e) { if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { Label categoryTitle = e.Item.FindControl("lbTitle") as Label; Category bindingCategory = categories[categoryTitle.Text]; if (bindingCategory != null && bindingCategory.Items.Count > 0) { Repeater childRepeater = (Repeater)e.Item.FindControl("rptSubCategoryList"); childRepeater.DataSource = bindingCategory.Items; childRepeater.DataBind(); } else if (categoryTitle.Text.Equals("Custom Data", StringComparison.OrdinalIgnoreCase)) { TextBox txtSelectedFile = e.Item.FindControl("txtSelectedFilePath") as TextBox; Button btnBrowse = e.Item.FindControl("btnBrowse") as Button; txtSelectedFile.Visible = true; btnBrowse.Visible = true; } } } private Collection<CategoryItem> GetCategoryItemByAlias(Collection<string> requestAliases, ref Category queriedCategory) { Collection<CategoryItem> queriedItems = new Collection<CategoryItem>(); foreach (var category in categories) { foreach (var item in category.Value.Items) { if (requestAliases.Contains(item.Alias)) { queriedCategory = category.Value; queriedItems.Add(item); } } } return queriedItems; } private void UpdateLegend(DemographicStyleBuilder styleBuilder) { LegendAdornmentLayer legendAdornmentLayer = Map1.AdornmentOverlay.Layers[0] as LegendAdornmentLayer; legendAdornmentLayer.LegendItems.Clear(); if (styleBuilder is ThematicDemographicStyleBuilder) { AddThematicLegendItems(styleBuilder, legendAdornmentLayer); } else if (styleBuilder is DotDensityDemographicStyleBuilder) { AddDotDensityLegendItems(styleBuilder, legendAdornmentLayer); } else if (styleBuilder is ValueCircleDemographicStyleBuilder) { AddValueCircleLegendItems(styleBuilder, legendAdornmentLayer); } else if (styleBuilder is PieChartDemographicStyleBuilder) { AddPieGraphLegendItems(styleBuilder, legendAdornmentLayer); } legendAdornmentLayer.ContentResizeMode = LegendContentResizeMode.Fixed; legendAdornmentLayer.Height = GetLegendHeight(legendAdornmentLayer); legendAdornmentLayer.Width = GetLegendWidth(legendAdornmentLayer); } private void AddPieGraphLegendItems(DemographicStyleBuilder styleBuilder, LegendAdornmentLayer legendAdornmentLayer) { ShapeFileFeatureLayer statesLayer = Map1.DynamicOverlay.Layers["usStatesLayer"] as ShapeFileFeatureLayer; PieZedGraphStyle zedGraphStyle = (PieZedGraphStyle)styleBuilder.GetStyle(statesLayer.FeatureSource); foreach (KeyValuePair<string, GeoColor> item in zedGraphStyle.PieSlices) { LegendItem legendItem = new LegendItem(); legendItem.ImageWidth = 20; legendItem.TextRightPadding = 5; legendItem.RightPadding = 5; legendItem.ImageStyle = new AreaStyle(new GeoSolidBrush(item.Value)); legendItem.TextStyle = new TextStyle(item.Key, new GeoFont("Segoe UI", 10), new GeoSolidBrush(GeoColor.SimpleColors.Black)); legendAdornmentLayer.LegendItems.Add(legendItem); } } private void AddValueCircleLegendItems(DemographicStyleBuilder styleBuilder, LegendAdornmentLayer legendAdornmentLayer) { ShapeFileFeatureLayer statesLayer = Map1.DynamicOverlay.Layers["usStatesLayer"] as ShapeFileFeatureLayer; ValueCircleStyle valueCircleStyle = (ValueCircleStyle)styleBuilder.GetStyle(statesLayer.FeatureSource); int[] circleAreas = new int[] { 160, 320, 640, 1280 }; foreach (int circleArea in circleAreas) { LegendItem legendItem = new LegendItem(); double radius = Math.Sqrt(circleArea / Math.PI); legendItem.ImageStyle = new PointStyle(PointSymbolType.Circle, new GeoSolidBrush(valueCircleStyle.InnerColor), new GeoPen(new GeoSolidBrush(valueCircleStyle.OuterColor)), (int)(radius * 2)); AreaStyle maskStyle = new AreaStyle(new GeoPen(GeoColor.StandardColors.LightGray, 1), new GeoSolidBrush(GeoColor.SimpleColors.Transparent)); legendItem.ImageMask = maskStyle; legendItem.ImageWidth = 48; legendItem.TextTopPadding = 16; legendItem.TextRightPadding = 5; legendItem.BottomPadding = 16; legendItem.TopPadding = 16; legendItem.RightPadding = 5; double drawingRadius = circleArea / valueCircleStyle.DrawingRadiusRatio * valueCircleStyle.BasedScale / valueCircleStyle.DefaultZoomLevel.Scale; double ratio = (valueCircleStyle.MaxValidValue - valueCircleStyle.MinValidValue) / (valueCircleStyle.MaxCircleAreaInDefaultZoomLevel - valueCircleStyle.MinCircleAreaInDefaultZoomLevel); double resultValue = (drawingRadius - valueCircleStyle.MinCircleAreaInDefaultZoomLevel) * ratio + valueCircleStyle.MinValidValue; string text = DemographicStyleTextFormatter.GetFormatedStringForLegendItem(valueCircleStyle.ColumnName, resultValue); legendItem.TextStyle = new TextStyle(text, new GeoFont("Segoe UI", 10), new GeoSolidBrush(GeoColor.SimpleColors.Black)); legendAdornmentLayer.LegendItems.Add(legendItem); } } private void AddDotDensityLegendItems(DemographicStyleBuilder styleBuilder, LegendAdornmentLayer legendAdornmentLayer) { ShapeFileFeatureLayer statesLayer = Map1.DynamicOverlay.Layers["usStatesLayer"] as ShapeFileFeatureLayer; CustomDotDensityStyle dotDensityStyle = (CustomDotDensityStyle)styleBuilder.GetStyle(statesLayer.FeatureSource); int[] pointCounts = new int[] { 5, 10, 20, 50 }; foreach (int pointCount in pointCounts) { LegendItem legendItem = new LegendItem(); legendItem.ImageMask = new AreaStyle(new GeoPen(GeoColor.StandardColors.LightGray, 1), new GeoSolidBrush(GeoColor.SimpleColors.Transparent)); legendItem.ImageWidth = 48; legendItem.TextTopPadding = 16; legendItem.TextRightPadding = 5; legendItem.BottomPadding = 16; legendItem.TopPadding = 16; legendItem.RightPadding = 5; CustomDotDensityStyle legendDotDensityStyle = (CustomDotDensityStyle)dotDensityStyle.CloneDeep(); legendDotDensityStyle.DrawingPointsNumber = pointCount; legendItem.ImageStyle = legendDotDensityStyle; string text = string.Format(CultureInfo.InvariantCulture, "{0:0.####}", DemographicStyleTextFormatter.GetFormatedStringForLegendItem(dotDensityStyle.ColumnName, (pointCount / dotDensityStyle.PointToValueRatio))); legendItem.TextStyle = new TextStyle(text, new GeoFont("Segoe UI", 10), new GeoSolidBrush(GeoColor.SimpleColors.Black)); legendAdornmentLayer.LegendItems.Add(legendItem); } } private void AddThematicLegendItems(DemographicStyleBuilder styleBuilder, LegendAdornmentLayer legendAdornmentLayer) { ShapeFileFeatureLayer statesLayer = Map1.DynamicOverlay.Layers["usStatesLayer"] as ShapeFileFeatureLayer; ClassBreakStyle thematicStyle = (ClassBreakStyle)styleBuilder.GetStyle(statesLayer.FeatureSource); for (int i = 0; i < thematicStyle.ClassBreaks.Count; i++) { LegendItem legendItem = new LegendItem(); if (i < thematicStyle.ClassBreaks.Count) { legendItem.ImageStyle = thematicStyle.ClassBreaks[i].DefaultAreaStyle; legendItem.ImageWidth = 20; legendItem.TextRightPadding = 5; legendItem.RightPadding = 5; string text = string.Empty; if (i != thematicStyle.ClassBreaks.Count - 1) { text = string.Format("{0:#,0.####} ~ {1:#,0.####}", DemographicStyleTextFormatter.GetFormatedStringForLegendItem(thematicStyle.ColumnName, thematicStyle.ClassBreaks[i].Value), DemographicStyleTextFormatter.GetFormatedStringForLegendItem(thematicStyle.ColumnName, thematicStyle.ClassBreaks[i|+ 1].Value)); } else { text = string.Format("> {0:#,0.####}", DemographicStyleTextFormatter.GetFormatedStringForLegendItem(thematicStyle.ColumnName, thematicStyle.ClassBreaks[i].Value)); } legendItem.TextStyle = new TextStyle(text, new GeoFont("Segoe UI", 10), new GeoSolidBrush(GeoColor.SimpleColors.Black)); } legendAdornmentLayer.LegendItems.Add(legendItem); } } public float GetLegendWidth(LegendAdornmentLayer legendAdornmentLayer) { GdiPlusGeoCanvas gdiPlusGeoCanvas = new GdiPlusGeoCanvas(); LegendItem title = legendAdornmentLayer.Title; float width = gdiPlusGeoCanvas.MeasureText(title.TextStyle.TextColumnName, new GeoFont("Segoe UI", 12)).Width + title.ImageWidth + title.ImageRightPadding + title.ImageLeftPadding + title.TextRightPadding + title.TextLeftPadding + title.LeftPadding + title.RightPadding; foreach (LegendItem legendItem in legendAdornmentLayer.LegendItems) { float legendItemWidth = gdiPlusGeoCanvas.MeasureText(legendItem.TextStyle.TextColumnName, new GeoFont("Segoe UI", 10)).Width + legendItem.ImageWidth + legendItem.ImageRightPadding + legendItem.ImageLeftPadding + legendItem.TextRightPadding + legendItem.TextLeftPadding + legendItem.LeftPadding + legendItem.RightPadding; if (width < legendItemWidth) { width = legendItemWidth; } } return width; } public float GetLegendHeight(LegendAdornmentLayer legendAdornmentLayer) { GdiPlusGeoCanvas gdiPlusGeoCanvas = new GdiPlusGeoCanvas(); LegendItem title = legendAdornmentLayer.Title; float legendHeight = Math.Max(gdiPlusGeoCanvas.MeasureText(title.TextStyle.TextColumnName, new GeoFont("Segoe UI", 12)).Height, title.ImageHeight); legendHeight = Math.Max(legendHeight, title.Height); float height = legendHeight + Math.Max(title.ImageTopPadding, title.TextTopPadding) + title.TopPadding + Math.Max(title.ImageBottomPadding, title.TextBottomPadding) + title.BottomPadding; foreach (LegendItem legendItem in legendAdornmentLayer.LegendItems) { float itemLegendHeight = Math.Max(gdiPlusGeoCanvas.MeasureText(legendItem.TextStyle.TextColumnName, new GeoFont("Segoe UI", 10)).Height, legendItem.ImageHeight); float itemHeight = itemLegendHeight + Math.Max(legendItem.ImageTopPadding, legendItem.TextTopPadding) + legendItem.TopPadding + Math.Max(legendItem.ImageBottomPadding, legendItem.TextBottomPadding) + legendItem.BottomPadding; height += itemHeight; } return height; } private void InitializeMapControl() { Map1.MapUnit = GeographyUnit.DecimalDegree; Map1.MapTools.Logo.Enabled = true; Map1.MapBackground.BackgroundBrush = new GeoSolidBrush(GeoColor.FromHtml("#E5E3DF")); Map1.CurrentExtent = new RectangleShape(-128.17864375, 56.9286546875, -69.11614375, 20.1903734375); // base map layers WorldMapKitWmsWebOverlay worldMapKitOverlay = new WorldMapKitWmsWebOverlay(); Map1.CustomOverlays.Add(worldMapKitOverlay); // us states layer ShapeFileFeatureLayer statesLayer = new ShapeFileFeatureLayer(Server.MapPath(ConfigurationManager.AppSettings["UsShapefilePath"])); ThematicDemographicStyleBuilder selectedStyle = new ThematicDemographicStyleBuilder(new Collection<string>() { "Population" }); statesLayer.ZoomLevelSet.ZoomLevel01.CustomStyles.Add(selectedStyle.GetStyle(statesLayer.FeatureSource)); statesLayer.ZoomLevelSet.ZoomLevel01.ApplyUntilZoomLevel = ApplyUntilZoomLevel.Level20; Map1.DynamicOverlay.Layers.Add("usStatesLayer", statesLayer); // highlight layers Map1.HighlightOverlay.HighlightStyle = new FeatureOverlayStyle(GeoColor.FromArgb(150, GeoColor.FromHtml("#449FBC")), GeoColor.FromHtml("#014576"), 1); Map1.HighlightOverlay.Style = new FeatureOverlayStyle(GeoColor.SimpleColors.Transparent, GeoColor.SimpleColors.Transparent, 0); statesLayer.Open(); foreach (Feature feature in statesLayer.FeatureSource.GetAllFeatures(ReturningColumnsType.NoColumns)) { Map1.HighlightOverlay.Features.Add(feature.Id, feature); } statesLayer.Close(); // Add hover-popup CloudPopup featureinfoPopup = new CloudPopup("featureInfoPopup", new PointShape(-300, -200), "State Info"); // make the popup out of map view temporarily featureinfoPopup.AutoSize = true; Map1.Popups.Add(featureinfoPopup); // Add Legend adorment overlay LegendAdornmentLayer legendAdornmentLayer = new LegendAdornmentLayer(); legendAdornmentLayer.Location = AdornmentLocation.LowerLeft; legendAdornmentLayer.XOffsetInPixel = 15; legendAdornmentLayer.Title = new LegendItem(); legendAdornmentLayer.Title.ImageJustificationMode = LegendImageJustificationMode.JustifyImageRight; legendAdornmentLayer.Title.TopPadding = 10; legendAdornmentLayer.Title.BottomPadding = 10; legendAdornmentLayer.Title.TextStyle = new TextStyle("Population", new GeoFont("Segoe UI", 12), new GeoSolidBrush(GeoColor.SimpleColors.Black)); Map1.AdornmentOverlay.Layers.Add(legendAdornmentLayer); ThematicDemographicStyleBuilder initDemographicStyle = new ThematicDemographicStyleBuilder(new Collection<string>() { "Population" }); UpdateLegend(initDemographicStyle); } private Dictionary<string, Category> LoadCategories() { var xDoc = XDocument.Load(Server.MapPath(ConfigurationManager.AppSettings["CategoryFilePath"])); var elements = from category in xDoc.Element("DemographicMap").Elements("Category") select category; Dictionary<string, Category> categories = new Dictionary<string, Category>(); foreach (var element in elements) { Category category = new Category(); category.Title = element.Attribute("name").Value; category.CategoryImage = element.Attribute("icon").Value; foreach (var item in element.Elements("item")) { CategoryItem categoryItem = new CategoryItem(); categoryItem.ColumnName = item.Element("columnName").Value; categoryItem.Alias = item.Element("alias").Value; category.Items.Add(categoryItem); } categories.Add(category.Title, category); } return categories; } } }
$(document).ready(function () { initializePageElements(); // apply the selected style to server side var applyStyleToServer = function (args) { var argsInString = JSON.stringify(args); $("#clientStatusKeeper").text(argsInString); // keep last request status // Remove the not supported charactor in URL if (argsInString.indexOf('>=') >= 0) { argsInString = argsInString.replace('>=', '$'); } $DoCallback(argsInString, function (result, context) { MapHelper.getDynamicOverlay().redraw(true); MapHelper.getAdormentOverlay().redraw(true); }, this); }; // Apply events to color picker var updateMapColorSystem = function (sliderVal) { var requestArgs = $("#clientStatusKeeper").text(); if ($.trim(requestArgs) != //) { var args = $.parseJSON(requestArgs); args["request"] = "applyStyle"; args["startColor"] = $('#colorStartselector').val(); args["endColor"] = $('#colorEndselector').val(); args["colorDirection"] = $('#slColorWheelDirection').val(); if (arguments.length > 0 && !isNaN(parseInt(sliderVal))) args["sliderValue"] = sliderVal; applyStyleToServer(args); } } $("#slColorWheelDirection").change(updateMapColorSystem); $('#colorStartselector').colorselector({ callback: updateMapColorSystem }); // show pie button after actived var refreshPieButton = function () { var activeIndex = parseInt($("#accordion").accordion("option", "active")); var accordionHeaders = $("#accordion h3"); var accordionContents = $('#accordion ul'); for (var i = 0; i < accordionHeaders.length; i++) { var pieButton = $(accordionHeaders[i]).find("input")[0]; var categoryItems = $(accordionContents[i]).find("Span"); if (activeIndex == i && categoryItems.length > 1) { $(pieButton).css('visibility', 'visible'); } else { $(pieButton).css('visibility', 'hidden'); } } } $("#accordion h3").click(refreshPieButton); refreshPieButton(); // Change style and do redraw map $("img[class='accordion-content-right']").click(function () { var alias = $.trim($(this).parent().find(".accordion-content").text()); applyStyleToServer({ "request": "applyStyle", "style": this.alt, "alias": alias }); resetConfigurations(this.alt); return false; }); // attach checkbox changed event and redraw map getActivePieButton = function () { var activeIndex = parseInt($("#accordion").accordion("option", "active")); return $("input[class='accordion-header-right'][type='image']")[activeIndex]; }; $("#accordion ul [type='checkbox']").change(function () { var activeIndex = parseInt($("#accordion").accordion("option", "active")); // get all the seleceted category items var activeContent = $('#accordion ul')[activeIndex]; var checkboxes = $(activeContent).find("[type='checkbox']"); var selectedItems = new Array(); for (var i = 0; i < checkboxes.length; i++) { if (checkboxes[i].checked) { var itemAlias = $(checkboxes[i]).parent().find("Span").text(); selectedItems.push($.trim(itemAlias)); } } var pieButton = getActivePieButton(); if (selectedItems.length > 1) { applyStyleToServer({ "request": "applyStyle", "style": "Pie", "selectedItems": selectedItems, "startColor": $('#colorStartselector').val() }); resetConfigurations("Pie"); $(pieButton).css('visibility', 'visible'); } else { $(pieButton).css('visibility', 'hidden'); } return false; }); // Deal with pie button click event $("input[class='accordion-header-right'][type='image']").click(function () { // get all the seleceted category items var activeIndex = parseInt($("#accordion").accordion("option", "active")); var activeContent = $('#accordion ul')[activeIndex]; var checkboxes = $(activeContent).find("[type='checkbox']"); var selectedItems = new Array(); for (var i = 0; i < checkboxes.length; i++) { if (checkboxes[i].checked) { var itemAlias = $(checkboxes[i]).parent().find("Span").text(); selectedItems.push($.trim(itemAlias)); $(checkboxes[i]).css("visibility", "visible"); } } applyStyleToServer({ "request": "applyStyle", "style": this.alt, "selectedItems": selectedItems, "startColor": $('#colorStartselector').val() }); resetConfigurations(this.alt); return false; }); // set default style as Population thematic var activeContent = $('#accordion ul')[0]; var themeticButton = $(activeContent).find("img")[1]; $(themeticButton).trigger("click"); // Init slider bar $("#slider").slider({ min: 1, max: 5, range: "min", value: 3, slide: function (event, ui) { updateMapColorSystem(ui.value); } }); }); var MapHelper = { getDynamicOverlay: function () { var map = Map1.GetOpenLayersMap(); return map.getLayer("DynamicOverlay"); }, getAdormentOverlay: function () { var adornmentOverlay = Map1.GetOpenLayersMap().getLayersByName("AdornmentOverlay"); return adornmentOverlay[0]; }, getPopup: function () { var map = Map1.GetOpenLayersMap(); return map.getPopup("featureInfoPopup"); } } // All the codes before creating map var OnMapCreating = function (map) { OpenLayers.Map.prototype.getPopup = function (id) { var searched = null; for (var i = 0; i < map.popups.length; i++) { if (map.popups[i].id == id) { searched = map.popups[i]; break; } } return searched; } } var popupDisplayTimer; var OnMapCreated = function (map) { // Show mouse coordinates on the page bottom map.events.register("mousemove", map, function (e) { var mouseCoordinate = this.getLonLatFromPixel(new OpenLayers.Pixel(e.clientX, e.clientY)); $("#spanMouseCoordinate").text("X:" + mouseCoordinate.lon.toFixed(6) + " Y: " + mouseCoordinate.lat.toFixed(6)); }) // Initialize the hover-popup var hightlightLayer = map.getLayer("HighlightOverlay"); hightlightLayer.events.register("mouseout", hightlightLayer, function (e) { // Clear timer at first window.clearTimeout(popupDisplayTimer); MapHelper.getPopup().hide(); }); hightlightLayer.events.register("mouseover", hightlightLayer, function (e) { var map = Map1.GetOpenLayersMap(); var lonlat = map.getLonLatFromPixel(new OpenLayers.Pixel(e.offsetX, e.offsetY)); var mouseCoordinate = new OpenLayers.Geometry.Point(lonlat.lon, lonlat.lat); var selectedFeature = null; for (var i = 0; i < hightlightLayer.features.length; i++) { if (hightlightLayer.features[i].geometry.intersects(mouseCoordinate)) { selectedFeature = hightlightLayer.features[i]; break; } } // Clear timer at first window.clearTimeout(popupDisplayTimer); if (selectedFeature != null) { var requestArgs = $("#clientStatusKeeper").text(); if ($.trim(requestArgs) != //) { var args = $.parseJSON(requestArgs); args["selectedFeatureId"] = selectedFeature.id; args['request'] = "identify"; popupDisplayTimer = window.setTimeout(function () { $DoCallback(JSON.stringify(args), function (result, context) { var featureInfoPopup = MapHelper.getPopup(); featureInfoPopup.setContentHTML(result); featureInfoPopup.lonlat = context; featureInfoPopup.updatePosition(); featureInfoPopup.show(); }, lonlat); }, 1000); } } }); } function initializePageElements() { var resizeElementHeight = function () { var documentheight = $(window).height(); var mapDivH = (documentheight - $("#header").height() - $("#footer").height() - 1) + "px"; $("#map-content").height(mapDivH); $("#leftContainer").height(mapDivH); $("#toggle").height(mapDivH); $("#toggle").css("line-height", mapDivH); // refresh the map. Map1.GetOpenLayersMap().updateSize(); } window.onload = resizeElementHeight(); $(window).resize(resizeElementHeight); // init accordion tree $("#accordion").accordion({ icons: null, heightStyle: "content" }); $("#accordion").accordion("option", "active", 0); // init color picker and color direction var initColorPicker = function (select) { var colors = getHtmlKnownColors(); for (var item in colors) { var option = new Option(item, colors[item]); $(option).attr("data-color", colors[item]); $(select).append(option); } } initColorPicker($("#colorStartselector")); initColorPicker($("#colorEndselector")); // Bind toggle button events $("#toggle img").bind("click", function () { if ($("#leftContainer").is(':visible')) { $(this).attr("src", "Images/expand.gif"); $("#map-content").css("width", "100%"); $("#toggle").css("left", "0%"); $("#leftContainer").hide(); } else { $("#leftContainer").show(); $(this).attr("src", "Images/collapse.gif") $("#map-content").css("width", "80%"); $("#toggle").css("left", "20%"); } resizeElementHeight(); }); } function resetConfigurations(style) { switch (style) { case "Thematic": $('#colorStartselector').colorselector("setColor", "#74a0ff"); $('#colorEndselector').colorselector("setColor", "#dc3438"); $("#spanBaseColor").text("Display Start Color:"); $("#divEndColor").show(); $("#divColorWheel").show(); $("#divSlider").hide(); break; case "DotDensity": $('#colorStartselector').colorselector("setColor", "#8B0000"); $("#spanBaseColor").text("Display Color:"); $("#divEndColor").hide(); $("#divColorWheel").hide(); $("#divSlider").show(); $("#spanSliderTitle").text("DotDensity Unit:"); break; case "ValueCircle": $('#colorStartselector').colorselector("setColor", "#ff7f00"); $("#spanBaseColor").text("Display Color:"); $("#divEndColor").hide(); $("#divColorWheel").hide(); $("#divSlider").show(); $("#spanSliderTitle").text("MAGNIFICATION:"); break; default: $("#divSlider").hide(); $("#divEndColor").hide(); $("#divColorWheel").hide(); $("#spanBaseColor").text("Display Color:"); $('#colorStartselector').colorselector("setColor", "#74a0ff"); break; } } function $DoCallback(arg, callbackEvent, context) { WebForm_DoCallback("__Page", arg, callbackEvent, context, null, false); } function getHtmlKnownColors() { var colors = { "Balck": "#000000", "White": "#FFFFFF", "Aqua": "#00FFFF", "MidnightBlue": "#191970", "DodgerBlue": "#1E90FF", "LightSeaGreen": "#20B2AA", "ForestGreen": "#228B22", "SeaGreen": "#2E8B57", "DarkSlateGray": "#2F4F4F", "LimeGreen": "#32CD32", "MediumSeaGreen": "#3CB371", "Turquoise": "#40E0D0", "SteelBlue": "#4682B4", "DarkSlateBlue": "#483D8B", "MediumTurquoise": "#48D1CC", "DarkOliveGreen": "#556B2F", "CadetBlue": "#5F9EA0", "MediumAquaMarine": "#66CDAA", "DimGray": "#696969", "SlateBlue": "#6A5ACD", "OliveDrab": "#6B8E23", "SlateGray": "#708090", "LightSlateGray": "#778899", "MediumSlateBlue": "#7B68EE", "Aquamarine": "#7FFFD4", "Maroon": "#800000", "Olive": "#808000", "Gray": "#808080", "SkyBlue": "#87CEEB", "BlueViolet": "#8A2BE2", "DarkRed": "#8B0000", "SaddleBrown": "#8B4513", "DarkSeaGreen": "#8FBC8F", "LightGreen": "#90EE90", "MediumPurple": "#9370DB", "PaleGreen": "#98FB98", "YellowGreen": "#9ACD32", "Sienna": "#A0522D", "DarkGray": "#A9A9A9", "LightBlue": "#74a0ff", "GreenYellow": "#ADFF2F", "Yellow ": "#FFFF00", "PaleTurquoise": "#AFEEEE", "LightSteelBlue": "#B0C4DE", "PowderBlue": "#B0E0E6", "FireBrick": "#B22222", "DarkGoldenRod": "#B8860B", "MediumOrchid": "#BA55D3", "RosyBrown": "#BC8F8F", "DarkKhaki": "#BDB76B", "Silver": "#C0C0C0", "MediumVioletRed": "#C71585", "IndianRed ": "#CD5C5C", "Peru": "#CD853F", "Chocolate": "#D2691E", "Tan": "#D2B48C", "LightGray": "#D3D3D3", "Thistle": "#D8BFD8", "Orchid": "#DA70D6", "GoldenRod": "#DAA520", "PaleVioletRed": "#DB7093", "Red": "#FF0000", "LightRed": "#dc3438", "Orange": "#ff7f00" }; return colors; }
using System.Collections.ObjectModel; using System.Runtime.Serialization; namespace ThinkGeo.MapSuite.USDemographicMap { [DataContract] public class JsonCallbackRequest { private string request; private string requestStyle; private string requestColumnAlias; private Collection<string> selectedCategoryItems; private string startColor; private string endColor; private string colorWheelDirection; private int sliderValue; private string selectedFeatureId; public JsonCallbackRequest() { } [DataMember(Name|= "request")] public string Request { get { return request; } set { request = value; } } public DemographicStyleBuilderType StyleBuildType { get { DemographicStyleBuilderType type = DemographicStyleBuilderType.Thematic; switch (requestStyle.ToLowerInvariant()) { case "pie": type = DemographicStyleBuilderType.PieChart; break; case "thematic": type = DemographicStyleBuilderType.Thematic; break; case "dotdensity": type = DemographicStyleBuilderType.DotDensity; break; case "valuecircle": type = DemographicStyleBuilderType.ValueCircle; break; } return type; } } [DataMember(Name|= "style")] private string RequestStyle { get { return requestStyle; } set { requestStyle = value; } } [DataMember(Name|= "alias")] public string RequestColumnAlias { get { return requestColumnAlias; } set { requestColumnAlias = value; } } [DataMember(Name|= "selectedItems")] public Collection<string> SelectedCategoryItems { get { return selectedCategoryItems; } internal set { selectedCategoryItems = value; } } [DataMember(Name|= "startColor")] public string StartColor { get { return startColor; } set { startColor = value; } } [DataMember(Name|= "endColor")] public string EndColor { get { return endColor; } set { endColor = value; } } [DataMember(Name|= "colorDirection")] public string ColorWheelDirection { get { return colorWheelDirection; } set { colorWheelDirection = value; } } [DataMember(Name|= "sliderValue")] public int SliderValue { get { return sliderValue; } set { sliderValue = value; } } [DataMember(Name|= "selectedFeatureId")] public string SelectedFeatureId { get { return selectedFeatureId; } set { selectedFeatureId = value; } } } }
using System.Collections.ObjectModel; using System.Web.UI; using ThinkGeo.MapSuite.Core; using ThinkGeo.MapSuite.WebEdition; using System.Configuration; namespace ThinkGeo.MapSuite.USDemographicMap { public class UsDemographicMap { private Map mapControl; private Page mainPage; private ShapeFileFeatureLayer statesLayer; private ThematicDemographicStyle selectedStyle; private UsDemographicMap() { } public UsDemographicMap(Map map, Page page) { this.mapControl = map; this.mainPage = page; } public Map MapControl { get { return mapControl; } } public Page MainPage { get { return mainPage; } } public ShapeFileFeatureLayer StatesLayer { get { return statesLayer; } } public ThematicDemographicStyle SelectedStyle { get { return selectedStyle; } set { selectedStyle = value; } } public void Initialize() { MapControl.MapUnit = GeographyUnit.DecimalDegree; MapControl.MapTools.Logo.Enabled = true; MapControl.MapBackground.BackgroundBrush = new GeoSolidBrush(GeoColor.FromHtml("#E5E3DF")); MapControl.CurrentExtent = new RectangleShape(-128.17864375, 56.9286546875, -69.11614375, 20.1903734375); // Display base-map WorldMapKitWmsWebOverlay worldMapKitOverlay = new WorldMapKitWmsWebOverlay(); MapControl.CustomOverlays.Add(worldMapKitOverlay); // Display US states with selected style statesLayer = new ShapeFileFeatureLayer(MainPage.Server.MapPath(ConfigurationManager.AppSettings["UsShapefilePath"])); statesLayer.Open(); Collection<string> basedColumns = new Collection<string>() { "Pop" }; SelectedStyle = new ThematicDemographicStyle(basedColumns); statesLayer.ZoomLevelSet.ZoomLevel01.CustomStyles.Add(SelectedStyle.GetStyle(statesLayer.FeatureSource)); statesLayer.ZoomLevelSet.ZoomLevel01.ApplyUntilZoomLevel = ApplyUntilZoomLevel.Level20; MapControl.DynamicOverlay.Layers.Add("usStatesLayer", statesLayer); // Display highlight overlay statesLayer.Open(); MapControl.HighlightOverlay.HighlightStyle = new FeatureOverlayStyle(GeoColor.FromArgb(100, GeoColor.StandardColors.LightBlue), GeoColor.StandardColors.White, 1); MapControl.HighlightOverlay.Style = new FeatureOverlayStyle(GeoColor.SimpleColors.Transparent, GeoColor.SimpleColors.Transparent, 0); foreach (Feature feature in statesLayer.FeatureSource.GetAllFeatures(ReturningColumnsType.NoColumns)) { MapControl.HighlightOverlay.Features.Add(feature.Id, feature); } statesLayer.Close(); } } }
using System; using System.Collections.ObjectModel; using ThinkGeo.MapSuite.Core; namespace ThinkGeo.MapSuite.USDemographicMap { [Serializable] class CustomDotDensityStyle : DotDensityStyle { private int drawingPointsNumber; public CustomDotDensityStyle() : base() { } public int DrawingPointsNumber { get { return drawingPointsNumber; } set { drawingPointsNumber = value; } } protected override void DrawSampleCore(GeoCanvas canvas, DrawingRectangleF drawingExtent) { base.DrawSampleCore(canvas, drawingExtent); PointShape upperLeftPoint = ExtentHelper.ToWorldCoordinate(canvas.CurrentWorldExtent, drawingExtent.CenterX - drawingExtent.Width / 2, drawingExtent.CenterY - drawingExtent.Height / 2, canvas.Width, canvas.Height); PointShape lowerRightPoint = ExtentHelper.ToWorldCoordinate(canvas.CurrentWorldExtent, drawingExtent.CenterX + drawingExtent.Width / 2, drawingExtent.CenterY + drawingExtent.Height / 2, canvas.Width, canvas.Height); RectangleShape rectangle = new RectangleShape(upperLeftPoint, lowerRightPoint); rectangle.ScaleDown(10); // Here draw the points on Legend Image Random random = new Random(DateTime.Now.Millisecond); Collection<BaseShape> drawingPoints = new Collection<BaseShape>(); for (int i = 0; i < DrawingPointsNumber; i++) { double x = rectangle.LowerLeftPoint.X + random.NextDouble() * (rectangle.Width); double y = rectangle.LowerLeftPoint.Y + random.NextDouble() * (rectangle.Height); drawingPoints.Add(new PointShape(x, y)); } TextStyle textStyle = new TextStyle(DrawingPointsNumber.ToString(), new GeoFont("Arial", 20, DrawingFontStyles.Bold), new GeoSolidBrush(GeoColor.FromArgb(180, GeoColor.FromHtml("#d3d3d3")))); textStyle.DrawSample(canvas, drawingExtent); CustomPointStyle.Draw(drawingPoints, canvas, new Collection<SimpleCandidate>(), new Collection<SimpleCandidate>()); } } }
using System.Collections.Generic; using System.Collections.ObjectModel; using ThinkGeo.MapSuite.Core; namespace ThinkGeo.MapSuite.USDemographicMap { public abstract class DemographicStyleBuilder { private GeoColor color; private int opacity; private Collection<string> selectedColumns; protected DemographicStyleBuilder() : this(new Collection<string>()) { } protected DemographicStyleBuilder(IEnumerable<string> selectedColumns) { this.Opacity = 100; this.color = GeoColor.FromHtml("#f1f369"); this.selectedColumns = new Collection<string>(new List<string>(selectedColumns)); } public Collection<string> SelectedColumns { get { return selectedColumns; } } public GeoColor Color { get { return color; } set { color = value; } } public int Opacity { get { return opacity; } set { opacity = value; } } public Style GetStyle(FeatureSource featureSource) { return GetStyleCore(featureSource); } protected abstract Style GetStyleCore(FeatureSource featureSource); } }
namespace ThinkGeo.MapSuite.USDemographicMap { public enum DemographicStyleBuilderType { Thematic = 0, ValueCircle = 1, DotDensity = 2, PieChart = 3 } }
using System; using System.Globalization; namespace ThinkGeo.MapSuite.USDemographicMap { public static class DemographicStyleTextFormatter { public static string GetFormatedStringForLegendItem(string columnName, double value) { string aliasUnitString = GetFormatedString(columnName, value); string[] subStrings = aliasUnitString.Split(new string[] { ": " }, StringSplitOptions.None); if (subStrings[subStrings.Length|- 1].Contains("%")) { aliasUnitString = subStrings[subStrings.Length|- 1]; } else { aliasUnitString = value.ToString("N0", CultureInfo.InvariantCulture); } return aliasUnitString; } public static string GetFormatedString(string columnName, double value) { string result = string.Empty; switch (columnName) { case "Population": result = string.Format("Population : {0} People", value.ToString("N0", CultureInfo.InvariantCulture)); break; case "PopDensity": result = string.Format("Population Density : {0} People/sq.mi.", value.ToString("N0", CultureInfo.InvariantCulture)); break; case "Female": result = string.Format("Female : {0}%", value.ToString("N2", CultureInfo.InvariantCulture)); break; case "Male": result = string.Format("Male : {0}%", value.ToString("N2", CultureInfo.InvariantCulture)); break; case "AREALAND": result = string.Format("Land Area : {0} sq.mi.", value.ToString("N2", CultureInfo.InvariantCulture)); break; case "AREAWATR": result = string.Format("Water Area : {0} sq.mi.", value.ToString("N2", CultureInfo.InvariantCulture)); break; case "White": result = string.Format("White : {0}%", value.ToString("N2", CultureInfo.InvariantCulture)); break; case "Black": result = string.Format("Black : {0}%", value.ToString("N2", CultureInfo.InvariantCulture)); break; case "Indian": result = string.Format("American Indian : {0}%", value.ToString("N2", CultureInfo.InvariantCulture)); break; case "Islander": result = string.Format("Native Pacific Islander : {0}%", value.ToString("N2", CultureInfo.InvariantCulture)); break; case "Asian": result = string.Format("Asian : {0}%", value.ToString("N2", CultureInfo.InvariantCulture)); break; case "Other": result = string.Format("Other : {0}%", value.ToString("N2", CultureInfo.InvariantCulture)); break; case "MultiRace": result = string.Format("Multiracial : {0}%", value.ToString("N2", CultureInfo.InvariantCulture)); break; case "Under5": result = string.Format("<= 5 : {0}%", value.ToString("N2", CultureInfo.InvariantCulture)); break; case "5to9": result = string.Format("5 ~ 10 : {0}%", value.ToString("N2", CultureInfo.InvariantCulture)); break; case "10to14": result = string.Format("10 ~ 15 : {0}%", value.ToString("N2", CultureInfo.InvariantCulture)); break; case "15to17": result = string.Format("15 ~ 18 : {0}%", value.ToString("N2", CultureInfo.InvariantCulture)); break; case "18to24": result = string.Format("18 ~ 25 : {0}%", value.ToString("N2", CultureInfo.InvariantCulture)); break; case "25to34": result = string.Format("25 ~ 35 : {0}%", value.ToString("N2", CultureInfo.InvariantCulture)); break; case "35to44": result = string.Format("35 ~ 45 : {0}%", value.ToString("N2", CultureInfo.InvariantCulture)); break; case "45to54": result = string.Format("45 ~ 55 : {0}%", value.ToString("N2", CultureInfo.InvariantCulture)); break; case "55to64": result = string.Format("55 ~ 65 : {0}%", value.ToString("N2", CultureInfo.InvariantCulture)); break; case "65to74": result = string.Format("65 ~ 75 : {0}%", value.ToString("N2", CultureInfo.InvariantCulture)); break; case "75to84": result = string.Format("75 ~ 85 : {0}%", value.ToString("N2", CultureInfo.InvariantCulture)); break; case "over85": result = string.Format(">= 85 : {0}%", value.ToString("N2", CultureInfo.InvariantCulture)); break; default: result = columnName + " : " + value.ToString("N0", CultureInfo.InvariantCulture); break; } return result; } } }
using System.Collections.Generic; using System.Globalization; using ThinkGeo.MapSuite.Core; namespace ThinkGeo.MapSuite.USDemographicMap { public class DotDensityDemographicStyleBuilder : DemographicStyleBuilder { private double dotDensityValue; public DotDensityDemographicStyleBuilder() : this(new string[] { }) { } public DotDensityDemographicStyleBuilder(IEnumerable<string> selectedColumns) : base(selectedColumns) { this.Opacity = 255; this.DotDensityValue = 50; this.Color = GeoColor.SimpleColors.DarkRed; } public double DotDensityValue { get { return dotDensityValue; } set { dotDensityValue = value; } } protected override Style GetStyleCore(FeatureSource featureSource) { double totalValue = 0; featureSource.Open(); int featureCount = featureSource.GetCount(); for (int i = 0; i < featureCount; i++) { Feature feature = featureSource.GetFeatureById((i + 1).ToString(CultureInfo.InvariantCulture), SelectedColumns); double columnValue; double.TryParse(feature.ColumnValues[SelectedColumns[0], out columnValue); totalValue += columnValue; } featureSource.Close(); double pointToValueRatio = DotDensityValue / (totalValue / featureCount); CustomDotDensityStyle dotDensityStyle = new CustomDotDensityStyle(); dotDensityStyle.ColumnName = SelectedColumns[0]; dotDensityStyle.PointToValueRatio = pointToValueRatio; dotDensityStyle.CustomPointStyle = new PointStyle(PointSymbolType.Circle, new GeoSolidBrush(GeoColor.FromArgb(Opacity, Color)), 4); return dotDensityStyle; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Drawing; using ThinkGeo.MapSuite.Core; using ZedGraph; namespace ThinkGeo.MapSuite.USDemographicMap { public class PieChartDemographicStyleBuilder : DemographicStyleBuilder { private Collection<string> selectedColumnAliases; private Collection<GeoColor> pieColors; public PieChartDemographicStyleBuilder() : base() { } public PieChartDemographicStyleBuilder(IEnumerable<string> selectedColumns) : base(selectedColumns) { this.Opacity = 200; this.Color = GeoColor.SimpleColors.LightBlue; } public Collection<string> SelectedColumnAliases { get { if (selectedColumnAliases == null) { selectedColumnAliases = new Collection<string>(); } return selectedColumnAliases; } } protected override Style GetStyleCore(FeatureSource featureSource) { PieZedGraphStyle zedGraphStyle = new PieZedGraphStyle(); zedGraphStyle.ZedGraphDrawing += new EventHandler<ZedGraphDrawingEventArgs>(zedGraphStyle_ZedGraphDrawing); pieColors = GeoColor.GetColorsInQualityFamily(GeoColor.FromArgb(Opacity, Color), SelectedColumns.Count); for (int i = 0; i < SelectedColumns.Count; i++) { zedGraphStyle.RequiredColumnNames.Add(SelectedColumns[i]); zedGraphStyle.PieSlices.Add(SelectedColumnAliases[i], pieColors[i]); } return zedGraphStyle; } void zedGraphStyle_ZedGraphDrawing(object sender, ZedGraphDrawingEventArgs e) { ZedGraphControl zedGraph = new ZedGraphControl(); zedGraph.Size = new Size(100, 100); zedGraph.GraphPane.Fill.Type = FillType.None; zedGraph.GraphPane.Chart.Fill.Type = FillType.None; zedGraph.GraphPane.Border.IsVisible = false; zedGraph.GraphPane.Chart.Border.IsVisible = false; zedGraph.GraphPane.XAxis.IsVisible = false; zedGraph.GraphPane.YAxis.IsVisible = false; zedGraph.GraphPane.Legend.IsVisible = false; zedGraph.GraphPane.Title.IsVisible = false; for (int i = 0; i < SelectedColumns.Count; i++) { Color color = System.Drawing.Color.FromArgb(pieColors[i].AlphaComponent, pieColors[i].RedComponent, pieColors[i].GreenComponent, pieColors[i].BlueComponent); PieItem pieItem = zedGraph.GraphPane.AddPieSlice(Convert.ToDouble(e.Feature.ColumnValues[SelectedColumns[i]), color, 0.08, ""); pieItem.LabelDetail.IsVisible = false; } zedGraph.AxisChange(); e.Bitmap = zedGraph.GraphPane.GetImage(); } } }
using System.Collections.Generic; using ThinkGeo.MapSuite.Core; namespace ThinkGeo.MapSuite.USDemographicMap { public class PieZedGraphStyle : ZedGraphStyle { private Dictionary<string, GeoColor> pieSlices; public PieZedGraphStyle() : base() { } public Dictionary<string, GeoColor> PieSlices { get { if (pieSlices == null) { pieSlices = new Dictionary<string, GeoColor>(); } return pieSlices; } } } }
using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using ThinkGeo.MapSuite.Core; namespace ThinkGeo.MapSuite.USDemographicMap { public class ThematicDemographicStyleBuilder : DemographicStyleBuilder { private int classBreakCount; private GeoColor endColor; private ColorWheelDirection colorWheelDirection; public ThematicDemographicStyleBuilder() : this(new string[] { }) { } public ThematicDemographicStyleBuilder(IEnumerable<string> selectedColumns) : base(selectedColumns) { this.ClassBreaksCount = 10; this.Color = GeoColor.SimpleColors.LightBlue; this.EndColor = GeoColor.SimpleColors.LightRed; this.ColorWheelDirection = ColorWheelDirection.CounterClockwise; this.Opacity = 200; } public int ClassBreaksCount { get { return classBreakCount; } set { classBreakCount = value; } } public ColorWheelDirection ColorWheelDirection { get { return colorWheelDirection; } set { colorWheelDirection = value; } } public GeoColor StartColor { get { return Color; } set { Color = value; } } public GeoColor EndColor { get { return endColor; } set { endColor = value; } } protected override Style GetStyleCore(FeatureSource featureSource) { Collection<GeoColor> familyColors = GeoColor.GetColorsInQualityFamily(Color, EndColor, classBreakCount, ColorWheelDirection); featureSource.Open(); int featureCount = featureSource.GetCount(); double[] values = new double[featureCount]; for (int i = 0; i < featureCount; i++) { Feature feature = featureSource.GetFeatureById((i + 1).ToString(CultureInfo.InvariantCulture), SelectedColumns); double columnValue; double.TryParse(feature.ColumnValues[SelectedColumns[0], out columnValue); values[i] = columnValue; } featureSource.Close(); ClassBreakStyle classBreakStyle = new ClassBreakStyle(SelectedColumns[0]) { BreakValueInclusion = BreakValueInclusion.IncludeValue }; double[] classBreakValues = GetClusterClassBreaks(values, ClassBreaksCount - 1); for (int i = 0; i < classBreakValues.Length; i++) { ClassBreak classBreak = new ClassBreak(classBreakValues[i], AreaStyles.CreateSimpleAreaStyle(new GeoColor(this.Opacity, familyColors[i]), GeoColor.FromHtml("#f05133"), 1)); classBreakStyle.ClassBreaks.Add(classBreak); } return classBreakStyle; } private double[] GetClusterClassBreaks(double[] values, int count) { var result = new List<double>(); var orderedValues = values.OrderBy(v => v).ToArray(); var min = orderedValues[0]; var max = orderedValues[orderedValues.Length|- 1]; var classesCount = (int)(orderedValues.Length / count); var breakValue = min; for (var i = 1; i < count; i++) { breakValue = orderedValues[i|* classesCount]; if (!result.Contains(breakValue)) { result.Add(breakValue); } } result.Insert(0, 0); return result.ToArray(); } } }
using System.Collections.Generic; using System.Globalization; using ThinkGeo.MapSuite.Core; namespace ThinkGeo.MapSuite.USDemographicMap { public class ValueCircleDemographicStyleBuilder : DemographicStyleBuilder { private double radiusRatio; public ValueCircleDemographicStyleBuilder() : this(new string[] { }) { } public ValueCircleDemographicStyleBuilder(IEnumerable<string> selectedColumns) : base(selectedColumns) { this.radiusRatio = 1; this.Color = GeoColor.SimpleColors.BrightOrange; this.Opacity = 160; } public double RadiusRatio { get { return radiusRatio; } set { radiusRatio = value; } } protected override Style GetStyleCore(FeatureSource featureSource) { double minValue = double.MaxValue; double maxValue = double.MinValue; featureSource.Open(); for (int i = 0; i < featureSource.GetCount(); i++) { Feature feature = featureSource.GetFeatureById((i + 1).ToString(CultureInfo.InvariantCulture), SelectedColumns); double columnValue; if (double.TryParse(feature.ColumnValues[SelectedColumns[0], out columnValue)) { if (columnValue < minValue) { minValue = columnValue; } else if (columnValue > maxValue) { maxValue = columnValue; } } } featureSource.Close(); ValueCircleStyle valueCircleStyle = new ValueCircleStyle(); valueCircleStyle.ColumnName = SelectedColumns[0]; valueCircleStyle.DrawingRadiusRatio = radiusRatio; valueCircleStyle.MinValidValue = minValue; valueCircleStyle.MaxValidValue = maxValue; valueCircleStyle.MinCircleAreaInDefaultZoomLevel = 80; valueCircleStyle.MaxCircleAreaInDefaultZoomLevel = 10000; valueCircleStyle.InnerColor = GeoColor.FromArgb(this.Opacity, Color); valueCircleStyle.OuterColor = GeoColor.SimpleColors.White; return valueCircleStyle; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using ThinkGeo.MapSuite.Core; namespace ThinkGeo.MapSuite.USDemographicMap { public class ValueCircleStyle : Style { private string columnName; private ZoomLevel defaultZoomLevel; private double drawingRadiusRatio; private GeoColor innerColor; private double maxCircleRadiusInDefaultZoomLevel; private double maxValidValue; private double minCircleRadiusInDefaultZoomLevel; private double minValidValue; private GeoColor outerColor; private double basedScale; public ValueCircleStyle() : base() { defaultZoomLevel = (new ZoomLevelSet()).ZoomLevel04; drawingRadiusRatio = 1; outerColor = GeoColor.FromArgb(255, 10, 20, 255); innerColor = GeoColor.FromArgb(100, 10, 20, 255); minCircleRadiusInDefaultZoomLevel = 10; maxCircleRadiusInDefaultZoomLevel = 100; basedScale = (new ZoomLevelSet()).ZoomLevel05.Scale; } public string ColumnName { get { return columnName; } set { columnName = value; } } public ZoomLevel DefaultZoomLevel { get { return defaultZoomLevel; } set { defaultZoomLevel = value; } } public double DrawingRadiusRatio { get { return drawingRadiusRatio; } set { drawingRadiusRatio = value; } } public GeoColor InnerColor { get { return innerColor; } set { innerColor = value; } } public double MaxCircleAreaInDefaultZoomLevel { get { return maxCircleRadiusInDefaultZoomLevel; } set { maxCircleRadiusInDefaultZoomLevel = value; } } public double MaxValidValue { get { return maxValidValue; } set { maxValidValue = value; } } public double MinCircleAreaInDefaultZoomLevel { get { return minCircleRadiusInDefaultZoomLevel; } set { minCircleRadiusInDefaultZoomLevel = value; } } public double MinValidValue { get { return minValidValue; } set { minValidValue = value; } } public GeoColor OuterColor { get { return outerColor; } set { outerColor = value; } } public double BasedScale { get { return basedScale; } } protected override void DrawCore(IEnumerable<Feature> features, GeoCanvas canvas, Collection<SimpleCandidate> labelsInThisLayer, Collection<SimpleCandidate> labelsInAllLayers) { double dCircleArea = maxCircleRadiusInDefaultZoomLevel - MinCircleAreaInDefaultZoomLevel; double dValue = maxValidValue - minValidValue; double ratio = dValue / dCircleArea; foreach (Feature f in features) { PointShape center = f.GetShape().GetCenterPoint(); double value = 0; if (!double.TryParse(f.ColumnValues[columnName], out value)) { continue; } if (value > maxValidValue || value < minValidValue) { continue; } double drawingDefaultCircleArea = (value - minValidValue) / ratio + minCircleRadiusInDefaultZoomLevel; double defaultScale = defaultZoomLevel.Scale; double scale = canvas.CurrentScale; double graphArea = 0, graphHeght = 0; graphArea = drawingDefaultCircleArea * defaultScale / basedScale * drawingRadiusRatio; graphHeght = Math.Sqrt(graphArea / Math.PI); canvas.DrawEllipse(center, (float)(graphHeght * 2), (float)(graphHeght * 2), new GeoPen(outerColor, 1), new GeoSolidBrush(innerColor), DrawingLevel.LevelOne); } } protected override Collection<string> GetRequiredColumnNamesCore() { Collection<string> requiredFieldNames = new Collection<string>(); requiredFieldNames.Add(columnName); return requiredFieldNames; } } }