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.EarthquakeStatistics._Default" %> <%@ Register Assembly="WebEdition" Namespace="ThinkGeo.MapSuite.WebEdition" TagPrefix="cc1" %> <!DOCTYPE html> <html xml:en-us"> <head> <title>US Earthquake Statistic</title> <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.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> <script src="Scripts/ready-functions.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 Earthquake Statistic</span> </div> </div> <div id="content-container"> <div id="leftContainer"> <div id="leftContent"> <h4> Display Type:</h4> <div id="divBasemaps"> <asp:ImageButton ID="btnHeatMap" runat="server" ToolTip="show the heat map" AlternateText="Heat Map" ImageUrl="Images/heatMap.png" /> <asp:ImageButton ID="btnPointMap" runat="server" ToolTip="show the point map" AlternateText="Regular Point Map" ImageUrl="Images/pointMap.png" /> <asp:ImageButton ID="btnIsolineMap" runat="server" ToolTip="show the isoline map" AlternateText="IsoLines Map" ImageUrl="Images/IsoLine.png" /> </div> <div id="divblueBanner"> Earthquake Information Explorer </div> <h4> Query Tool:</h4> <div id="divTrackShapes" class="divBorder"> <asp:ImageButton ID="btnPanMap" runat="server" ToolTip="Pan the map" CommandArgument="Pan" CssClass="active" OnCommand="ChangeTrackShapeMode_Command" ImageUrl="Images/Pan.png" /> <asp:ImageButton ID="btnDrawPolygon" runat="server" ToolTip="Draw a polygon" CommandArgument="DrawPolygon" OnCommand="ChangeTrackShapeMode_Command" ImageUrl="Images/DrawPolygon.png" /> <asp:ImageButton ID="btnDrawRectangle" runat="server" ToolTip="Draw a rectangle" CommandArgument="DrawRectangle" OnCommand="ChangeTrackShapeMode_Command" ImageUrl="Images/DrawRectangle.png" /> <asp:ImageButton ID="btnDrawCircle" runat="server" ToolTip="Draw a circle" CommandArgument="DrawCircle" OnCommand="ChangeTrackShapeMode_Command" ImageUrl="Images/Drawcircle.png" /> <asp:ImageButton ID="btnClearAll" runat="server" ToolTip="Clear all" CommandArgument="ClearAll" OnCommand="ChangeTrackShapeMode_Command" ImageUrl="Images/clear.png" /> </div> <h4> Query Configuration:</h4> <div id="divQueryPanel" class="divBorder"> <table> <tr> <td colspan="3"> <h5> Magnitude: </h5> </td> </tr> <tr> <td class="cfgRangeTitle"> <span>0</span> </td> <td class="slider"> <div id="sliderFortxbMagnitude"> </div> </td> <td class="cfgRangeTitle"> <span>12</span> </td> </tr> <tr> <td colspan="3"> <h5> Depth of Hypocenter(Km): </h5> </td> </tr> <tr> <td class="cfgRangeTitle"> <span>0</span> </td> <td class="slider"> <div id="sliderFortxbDepth"> </div> </td> <td class="cfgRangeTitle"> <span>300</span> </td> </tr> <tr> <td colspan="3"> <h5> Date(Year): </h5> </td> </tr> <tr> <td class="cfgRangeTitle"> <span>1568</span> </td> <td class="slider"> <div id="sliderFortxbYear"> </div> </td> <td class="cfgRangeTitle"> <span>2010</span> </td> </tr> </table> </div> </div> </div> <div id="toggle"> <img id="collapse" src="Images/collapse.gif" /> </div> <div id="map-content"> <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <div id="mapContainer"> <cc1:Map ID="Map1" runat="server" Width="100%" Height="100%" OnTrackShapeFinished="Map1_TrackShapeFinished"> </cc1:Map> </div> </ContentTemplate> <Triggers> <asp:AsyncPostBackTrigger ControlID="btnHeatMap" /> <asp:AsyncPostBackTrigger ControlID="btnPointMap" /> <asp:AsyncPostBackTrigger ControlID="btnIsolineMap" /> <asp:AsyncPostBackTrigger ControlID="btnPanMap" /> <asp:AsyncPostBackTrigger ControlID="btnDrawCircle" /> <asp:AsyncPostBackTrigger ControlID="btnDrawRectangle" /> <asp:AsyncPostBackTrigger ControlID="btnDrawPolygon" /> <asp:AsyncPostBackTrigger ControlID="btnClearAll" /> </Triggers> </asp:UpdatePanel> <div id="resultContainer"> <asp:UpdatePanel ID="UpdatePanel2" runat="server" ChildrenAsTriggers="false" UpdateMode="Conditional"> <ContentTemplate> <asp:Repeater ID="rptQueryResult" runat="server" OnItemDataBound="rptQueryResultItemDataBound" OnItemCommand="ibtnZoomToFeature"> <HeaderTemplate> <table id="resultTable"> <tr> <td class="result-header"> </td> <td class="result-header"> Year </td> <td class="result-header"> Longitude </td> <td class="result-header"> Latitude </td> <td class="result-header"> Depth(KM) </td> <td class="result-header"> Magnitude </td> <td class="result-header"> Location </td> </tr> </HeaderTemplate> <ItemTemplate> <tr> <td> <asp:ImageButton ID="find" runat="server" ImageUrl="/Images/find.png" /> </td> <td> <%# Eval("year")%> </td> <td> <%# Eval("longitude")%> </td> <td> <%# Eval("latitude")%> </td> <td> <%# Eval("depth_km")%> </td> <td> <%# Eval("magnitude")%> </td> <td> <%# Eval("location")%> </td> </tr> </ItemTemplate> <FooterTemplate> </table> </FooterTemplate> </asp:Repeater> </ContentTemplate> <Triggers> <asp:AsyncPostBackTrigger ControlID="Map1" /> <asp:AsyncPostBackTrigger ControlID="btnClearAll" /> </Triggers> </asp:UpdatePanel> </div> </div> </div> <div id="footer"> <span id="spanMouseCoordinate"></span> </div> <div id="loading"> <img id="loading-image" src="Images/loading.gif" alt="Loading..." /> </div> </div> </form> </body> </html>
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Configuration; using System.Data; using System.Linq; using System.Web.UI; using System.Web.UI.WebControls; using ThinkGeo.MapSuite.Core; using ThinkGeo.MapSuite.WebEdition; namespace ThinkGeo.MapSuite.EarthquakeStatistics { public partial class _Default : Page, ICallbackEventHandler { private string callbackResult; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { InitializeMap(); // display an empty query result table. DisplayQueryResult(new Collection<Feature>()); } } protected void ChangeTrackShapeMode_Command(object sender, CommandEventArgs e) { switch (e.CommandArgument.ToString()) { case "DrawCircle": Map1.EditOverlay.TrackMode = TrackMode.Circle; break; case "DrawRectangle": Map1.EditOverlay.TrackMode = TrackMode.Rectangle; break; case "DrawPolygon": Map1.EditOverlay.TrackMode = TrackMode.Polygon; break; case "ClearAll": ClearQueryResult(); break; case "Pan": default: Map1.EditOverlay.TrackMode = TrackMode.None; break; } } protected void rptQueryResultItemDataBound(object sender, RepeaterItemEventArgs e) { if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { var featureID = ((DataRowView)e.Item.DataItem)[0].ToString(); ImageButton update = (ImageButton)e.Item.FindControl("find"); update.CommandArgument = featureID; } } protected void ibtnZoomToFeature(object source, RepeaterCommandEventArgs e) { string featureId = ((ImageButton)(((RepeaterCommandEventArgs)(e)).CommandSource)).CommandArgument; ZoomToFeature(featureId); } protected void Map1_TrackShapeFinished(object sender, EventArgs e) { Collection<EarthquakeQueryConfiguration> queryConfigurations = new Collection<EarthquakeQueryConfiguration>(); if (Session["QueryConfiguration"] != null) { queryConfigurations = Session["QueryConfiguration"] as Collection<EarthquakeQueryConfiguration>; } Collection<Feature> selectedFeatures = FilterEarthquakePoints(queryConfigurations); DisplayQueryResult(selectedFeatures); } public string GetCallbackResult() { return callbackResult; } public void RaiseCallbackEvent(string eventArgument) { CallbackRequest callbackRequest = JsonSerializer.Deserialize<CallbackRequest>(eventArgument); switch (callbackRequest.Command) { case "Query": IEnumerable<Feature> selectedFeatures = FilterEarthquakePoints(callbackRequest.QueryConfigurations); Session["QueryConfiguration"] = callbackRequest.QueryConfigurations; callbackResult = InternalHelper.ConvertFeaturesToJson(selectedFeatures); break; case "ZoomToFeature": callbackResult = ZoomToFeature(callbackRequest.FeatureId); break; case "ChangeType": ChangeMapDisplayType(callbackRequest.MapDisplayType); break; default: break; } } private void ChangeMapDisplayType(string mapType) { LayerOverlay earthquakeOverlay = Map1.CustomOverlays["EarthquakeOverlay"] as LayerOverlay; foreach (Layer layer in earthquakeOverlay.Layers) { layer.IsVisible = false; } Layer selectedLayer = earthquakeOverlay.Layers[mapType]; selectedLayer.IsVisible = true; earthquakeOverlay.Redraw(); // if Isoline layer, then display its legend. if (mapType.Equals("IsoLines Map")) { Map1.AdornmentOverlay.Layers["IsoLineLevelLegendLayer"].IsVisible = true; } else { Map1.AdornmentOverlay.Layers["IsoLineLevelLegendLayer"].IsVisible = false; } } private void ClearQueryResult() { // clear the query result table. DisplayQueryResult(new Collection<Feature>()); // clear the tracked shapes. LayerOverlay trackShapeOverlay = Map1.CustomOverlays["TrackShapeOverlay"] as LayerOverlay; InMemoryFeatureLayer trackShapeLayer = trackShapeOverlay.Layers["TrackShapeLayer"] as InMemoryFeatureLayer; trackShapeLayer.InternalFeatures.Clear(); trackShapeOverlay.Redraw(); LayerOverlay queryResultMarkerOverlay = Map1.CustomOverlays["QueryResultMarkerOverlay"] as LayerOverlay; // clear the queried result markers from map. InMemoryFeatureLayer markerMemoryLayer = queryResultMarkerOverlay.Layers["MarkerMemoryLayer"] as InMemoryFeatureLayer; markerMemoryLayer.InternalFeatures.Clear(); // clear the highlighted result markers. InMemoryFeatureLayer markerMemoryHighLightLayer = queryResultMarkerOverlay.Layers["MarkerMemoryHighLightLayer"] as InMemoryFeatureLayer; markerMemoryHighLightLayer.InternalFeatures.Clear(); queryResultMarkerOverlay.Redraw(); // make map back to normal mode. Map1.EditOverlay.Features.Clear(); Map1.EditOverlay.TrackMode = TrackMode.None; } private string ZoomToFeature(string featureId) { LayerOverlay queryResultMarkerOverlay = Map1.CustomOverlays["QueryResultMarkerOverlay"] as LayerOverlay; InMemoryFeatureLayer markerMemoryLayer = queryResultMarkerOverlay.Layers["MarkerMemoryLayer"] as InMemoryFeatureLayer; InMemoryFeatureLayer markerMemoryHighLightLayer = queryResultMarkerOverlay.Layers["MarkerMemoryHighLightLayer"] as InMemoryFeatureLayer; Feature currentFeature = markerMemoryLayer.InternalFeatures.FirstOrDefault(f => f.Id == featureId); markerMemoryHighLightLayer.InternalFeatures.Clear(); markerMemoryHighLightLayer.InternalFeatures.Add(currentFeature); PointShape center = currentFeature.GetShape() as PointShape; Map1.ZoomTo(center, Map1.ZoomLevelSet.GetZoomLevels()[16].Scale); queryResultMarkerOverlay.Redraw(); return currentFeature.GetBoundingBox().GetWellKnownText(); } private Collection<Feature> FilterEarthquakePoints(Collection<EarthquakeQueryConfiguration> queryConfigurations) { IEnumerable<Feature> allFeatures = new Collection<Feature>(); if (Map1.EditOverlay.Features.Count > 0) { Feature queryFeature = Feature.Union(Map1.EditOverlay.Features); BaseShape queryShape = queryFeature.GetShape(); FeatureLayer currentEarthquakeLayer = (Map1.CustomOverlays["EarthquakeOverlay"] as LayerOverlay).Layers[0] as FeatureLayer; currentEarthquakeLayer.Open(); allFeatures = currentEarthquakeLayer.FeatureSource.GetFeaturesWithinDistanceOf(queryShape, Map1.MapUnit, DistanceUnit.Meter, 1, ReturningColumnsType.AllColumns); currentEarthquakeLayer.Close(); } // filter the feature based on the query configuration. allFeatures = allFeatures.Where((f) => { bool isIncluded = true; foreach (EarthquakeQueryConfiguration item in queryConfigurations) { double columnValue = double.Parse(f.ColumnValues[item.Parameter]); if ((columnValue > item.Maximum || columnValue < item.Minimum) && columnValue > 0) // nagetive means no record. { isIncluded = false; break; } } return isIncluded; }).ToList(); // clear the original markers and add new markers. LayerOverlay queryResultMarkerOverlay = Map1.CustomOverlays["QueryResultMarkerOverlay"] as LayerOverlay; InMemoryFeatureLayer markerMemoryLayer = queryResultMarkerOverlay.Layers["MarkerMemoryLayer"] as InMemoryFeatureLayer; markerMemoryLayer.InternalFeatures.Clear(); foreach (Feature item in allFeatures) { markerMemoryLayer.InternalFeatures.Add(item); } queryResultMarkerOverlay.Redraw(); LayerOverlay trackShapeOverlay = Map1.CustomOverlays["TrackShapeOverlay"] as LayerOverlay; // clear the original track shapes and add the new shapes. InMemoryFeatureLayer trackShapeLayer = trackShapeOverlay.Layers["TrackShapeLayer"] as InMemoryFeatureLayer; trackShapeLayer.InternalFeatures.Clear(); foreach (Feature item in Map1.EditOverlay.Features) { trackShapeLayer.InternalFeatures.Add(item); } trackShapeOverlay.Redraw(); return new Collection<Feature>(allFeatures.ToList()); } private void DisplayQueryResult(IEnumerable<Feature> features) { DataTable resultTable = InternalHelper.GetQueriedResultTableDefination(); foreach (Feature point in features) { DataRow dataRow = resultTable.NewRow(); dataRow["id"] = point.Id; dataRow["year"] = point.ColumnValues["YEAR"]; dataRow["longitude"] = point.ColumnValues["LONGITUDE"]; dataRow["latitude"] = point.ColumnValues["LATITIUDE"]; dataRow["depth_km"] = point.ColumnValues["DEPTH_KM"]; dataRow["magnitude"] = point.ColumnValues["MAGNITUDE"]; dataRow["location"] = point.ColumnValues["LOCATION"]; resultTable.Rows.Add(dataRow); } rptQueryResult.DataSource = resultTable; rptQueryResult.DataBind(); } private void InitializeMap() { Map1.MapUnit = GeographyUnit.Meter; Map1.MapTools.OverlaySwitcher.Enabled = true; Map1.MapTools.OverlaySwitcher.BaseOverlayTitle = " "; // add base layers. AddBaseMapLayers(); // add the earthquake layer to as the data source. AddEarthquakeLayers(); // add query shape layers, like track layer, marker layer and highlight layer etc. AddQueryResultLayers(); // add adorment layers AddAdormentLayers(); Map1.CurrentExtent = new RectangleShape(-14503631.6805645, 7498410.41581975, -7928840.70035357, 4171879.26511785); } private void AddBaseMapLayers() { WorldMapKitWmsWebOverlay worldMapKitOverlay = new WorldMapKitWmsWebOverlay("World Map Kit"); worldMapKitOverlay.Projection = WorldMapKitProjection.SphericalMercator; Map1.CustomOverlays.Add(worldMapKitOverlay); OpenStreetMapOverlay openStreetMapOverlay = new OpenStreetMapOverlay("Open Street Map"); Map1.CustomOverlays.Add(openStreetMapOverlay); BingMapsOverlay bingMapsAerialOverlay = new BingMapsOverlay("Bing Maps Aerial", BingMapsStyle.Aerial); Map1.CustomOverlays.Add(bingMapsAerialOverlay); BingMapsOverlay bingMapsRoadOverlay = new BingMapsOverlay("Bing Maps Road", BingMapsStyle.Road); Map1.CustomOverlays.Add(bingMapsRoadOverlay); } private void AddEarthquakeLayers() { LayerOverlay earthquakeOverlay = new LayerOverlay("EarthquakeOverlay"); //earthquakeOverlay.TileType = TileType.SingleTile; earthquakeOverlay.IsVisibleInOverlaySwitcher = false; Map1.CustomOverlays.Add(earthquakeOverlay); ManagedProj4Projection proj4 = new ManagedProj4Projection(); proj4.InternalProjectionParametersString = ManagedProj4Projection.GetDecimalDegreesParametersString(); proj4.ExternalProjectionParametersString = ManagedProj4Projection.GetSphericalMercatorParametersString(); string dataShapefileFilePath = Server.MapPath(ConfigurationManager.AppSettings["statesPathFileName"]); EarthquakeHeatFeatureLayer heatLayer = new EarthquakeHeatFeatureLayer(new ShapeFileFeatureSource(dataShapefileFilePath)); heatLayer.HeatStyle = new HeatStyle(10, 180, "MAGNITUDE", 0, 12, 100, DistanceUnit.Kilometer); heatLayer.FeatureSource.Projection = proj4; earthquakeOverlay.Layers.Add("Heat Map", heatLayer); ShapeFileFeatureLayer pointLayer = new ShapeFileFeatureLayer(dataShapefileFilePath); pointLayer.FeatureSource.Projection = proj4; pointLayer.ZoomLevelSet.ZoomLevel01.DefaultPointStyle = PointStyles.CreateSimpleCircleStyle(GeoColor.StandardColors.Red, 6, GeoColor.StandardColors.White, 1); pointLayer.ZoomLevelSet.ZoomLevel01.ApplyUntilZoomLevel = ApplyUntilZoomLevel.Level20; pointLayer.IsVisible = false; earthquakeOverlay.Layers.Add("Regular Point Map", pointLayer); EarthquakeIsoLineFeatureLayer isoLineLayer = new EarthquakeIsoLineFeatureLayer(new ShapeFileFeatureSource(dataShapefileFilePath)); isoLineLayer.FeatureSource.Projection = proj4; isoLineLayer.IsVisible = false; earthquakeOverlay.Layers.Add("IsoLines Map", isoLineLayer); } private void AddQueryResultLayers() { // define the track layer. LayerOverlay trackResultOverlay = new LayerOverlay("TrackShapeOverlay"); trackResultOverlay.IsVisibleInOverlaySwitcher = false; trackResultOverlay.TileType = TileType.SingleTile; Map1.CustomOverlays.Add(trackResultOverlay); InMemoryFeatureLayer trackResultLayer = new InMemoryFeatureLayer(); trackResultLayer.ZoomLevelSet.ZoomLevel01.DefaultAreaStyle = AreaStyles.CreateSimpleAreaStyle(GeoColor.FromArgb(80, GeoColor.SimpleColors.LightGreen), GeoColor.SimpleColors.White, 2); trackResultLayer.ZoomLevelSet.ZoomLevel01.DefaultLineStyle = LineStyles.CreateSimpleLineStyle(GeoColor.SimpleColors.Orange, 2, true); trackResultLayer.ZoomLevelSet.ZoomLevel01.DefaultPointStyle = PointStyles.CreateSimpleCircleStyle(GeoColor.SimpleColors.Orange, 10); trackResultLayer.ZoomLevelSet.ZoomLevel01.ApplyUntilZoomLevel = ApplyUntilZoomLevel.Level20; trackResultOverlay.Layers.Add("TrackShapeLayer", trackResultLayer); // define the marker and highlight layer for markers. LayerOverlay queryResultMarkerOverlay = new LayerOverlay("QueryResultMarkerOverlay"); queryResultMarkerOverlay.IsBaseOverlay = false; queryResultMarkerOverlay.IsVisibleInOverlaySwitcher = false; queryResultMarkerOverlay.TileType = TileType.SingleTile; Map1.CustomOverlays.Add(queryResultMarkerOverlay); InMemoryFeatureLayer markerMemoryLayer = new InMemoryFeatureLayer(); markerMemoryLayer.ZoomLevelSet.ZoomLevel01.DefaultPointStyle = PointStyles.CreateSimpleCircleStyle(GeoColor.SimpleColors.Gold, 8, GeoColor.SimpleColors.Orange, 1); markerMemoryLayer.ZoomLevelSet.ZoomLevel01.ApplyUntilZoomLevel = ApplyUntilZoomLevel.Level20; queryResultMarkerOverlay.Layers.Add("MarkerMemoryLayer", markerMemoryLayer); InMemoryFeatureLayer markerMemoryHighLightLayer = new InMemoryFeatureLayer(); PointStyle highLightStyle = new PointStyle(); highLightStyle.CustomPointStyles.Add(PointStyles.CreateSimpleCircleStyle(GeoColor.FromArgb(50, GeoColor.SimpleColors.Blue), 20, GeoColor.SimpleColors.LightBlue, 1)); highLightStyle.CustomPointStyles.Add(PointStyles.CreateSimpleCircleStyle(GeoColor.SimpleColors.LightBlue, 9, GeoColor.SimpleColors.Blue, 1)); markerMemoryHighLightLayer.ZoomLevelSet.ZoomLevel01.DefaultPointStyle = highLightStyle; markerMemoryHighLightLayer.ZoomLevelSet.ZoomLevel01.ApplyUntilZoomLevel = ApplyUntilZoomLevel.Level20; queryResultMarkerOverlay.Layers.Add("MarkerMemoryHighLightLayer", markerMemoryHighLightLayer); } private void AddAdormentLayers() { // ScaleBar ScaleBarAdornmentLayer scaleBarAdormentLayer = new ScaleBarAdornmentLayer(); scaleBarAdormentLayer.XOffsetInPixel = 10; scaleBarAdormentLayer.UnitFamily = UnitSystem.Metric; Map1.AdornmentOverlay.Layers.Add("ScaleBarAdormentLayer", scaleBarAdormentLayer); // Isoline legend adorment layer LegendAdornmentLayer isoLevelLegendLayer = new LegendAdornmentLayer(); isoLevelLegendLayer.IsVisible = false; isoLevelLegendLayer.Width = 85; isoLevelLegendLayer.Height = 320; isoLevelLegendLayer.Location = AdornmentLocation.LowerRight; isoLevelLegendLayer.ContentResizeMode = LegendContentResizeMode.Fixed; LegendItem legendTitle = new LegendItem(); legendTitle.TextStyle = new TextStyle("Magnitude", new GeoFont("Arial", 10), new GeoSolidBrush(GeoColor.StandardColors.Black)); legendTitle.TextLeftPadding = -20; isoLevelLegendLayer.LegendItems.Add(legendTitle); // add legend title // Legend items LayerOverlay earthquakeOverlay = Map1.CustomOverlays["EarthquakeOverlay"] as LayerOverlay; EarthquakeIsoLineFeatureLayer isoLineLayer = earthquakeOverlay.Layers["IsoLines|Map"] as EarthquakeIsoLineFeatureLayer; for (int i = 0; i < isoLineLayer.IsoLineLevels.Count; i++) { LegendItem legendItem = new LegendItem(); legendItem.TextStyle = new TextStyle(isoLineLayer.IsoLineLevels[i].ToString("f2"), new GeoFont("Arial", 10), new GeoSolidBrush(GeoColor.StandardColors.Black)); legendItem.ImageStyle = isoLineLayer.LevelClassBreakStyle.ClassBreaks[i].CustomStyles[0]; legendItem.ImageWidth = 25; isoLevelLegendLayer.LegendItems.Add(legendItem); } Map1.AdornmentOverlay.Layers.Add("IsoLineLevelLegendLayer", isoLevelLegendLayer); } } }
$(document).ready(function () { initializePageElements(); // Map display type $("#divBasemaps input[type='image']").bind("click", function () { var args = { "command": "ChangeType", "mapType": $(this).attr("alt") }; $DoCallback(args, function (result) { var map = Map1.GetOpenLayersMap(); var adornmentOverlay = map.getLayersByName("AdornmentOverlay"); adornmentOverlay[0].redraw(true); var earthquakeOverlay = map.getLayer("EarthquakeOverlay"); earthquakeOverlay.redraw(true); $("#loading").hide(); }) return false; }); $("#btnClearAll").bind("click", function () { $("#divTrackShapes input[type=image]").not($("#btnPanMap")).removeClass("active"); $("#btnPanMap").addClass("active"); }); // Configuration silder var filterEarthquakePoints = function () { var queryItems = []; var magnitude = { "name": "MAGNITUDE", "min": $("#sliderFortxbMagnitude").slider("values", 0), "max": $("#sliderFortxbMagnitude").slider("values", 1) }; queryItems.push(magnitude); var depth = { "name": "DEPTH_KM", "min": $("#sliderFortxbDepth").slider("values", 0), "max": $("#sliderFortxbDepth").slider("values", 1) }; queryItems.push(depth); var year = { "name": "YEAR", "min": $("#sliderFortxbYear").slider("values", 0), "max": $("#sliderFortxbYear").slider("values", 1) }; queryItems.push(year); var args = { "command": "Query", "configs": queryItems }; $DoCallback(args, displayQueryResult); } var displaySlideValue = function (element, ui) { var valueSpans = $(element).parent().parent().find("span"); $(valueSpans[0]).text(ui.values[0]); $(valueSpans[1]).text(ui.values[1]); } $("#sliderFortxbMagnitude").slider({ range: true, min: 0, max: 12, values: [0,|12], stop: filterEarthquakePoints, slide: function (event, ui) { displaySlideValue(this, ui); } }); $("#sliderFortxbDepth").slider({ range: true, min: 0, max: 300, values: [0,|300], stop: filterEarthquakePoints, slide: function (event, ui) { displaySlideValue(this, ui); } }); $("#sliderFortxbYear").slider({ range: true, min: 1568, max: 2010, values: [1568,|2010], stop: filterEarthquakePoints, slide: function (event, ui) { displaySlideValue(this, ui); } }); }); function initializePageElements() { var resizeElementHeight = function () { var documentheight = $(window).height(); var contentDivH = documentheight - $("#footer").height() - $("#header").height() - 1; $("#content-container").height(contentDivH + "px"); $("#leftContainer").height(contentDivH + "px"); $("#map-content").height(contentDivH + "px"); $("#toggle").css("line-height", contentDivH + "px"); var mapDivH = contentDivH - $("#resultContainer").height(); $("#mapContainer").height(mapDivH + "px"); // refresh the map. Map1.GetOpenLayersMap().updateSize(); } window.onload = resizeElementHeight(); $(window).resize(resizeElementHeight); // set the toggle style for group buttons $("#divTrackShapes input[type=image]").bind("click", function () { var btnImgs = $("#divTrackShapes input[type=image]"); for (var i = 0; i < btnImgs.length; i++) { $(btnImgs[i]).attr("class", ""); } $(this).attr("class", "active"); }); // Bind toggle button events $("#toggle img").bind("click", function () { if ($("#leftContainer").is(':visible')) { $("#map-content").css("width", "99%"); $("#resultContainer").css("width", "99%"); $("#toggle").css("left", "5px"); $("#leftContainer").hide(); $("#collapse").attr("src", "Images/expand.gif"); } else { $("#leftContainer").show(); $("#map-content").css("width", "80%"); $("#resultContainer").css("width", "80%"); $("#toggle").css("left", "20%"); $("#collapse").attr("src", "Images/collapse.gif"); } resizeElementHeight(); }); // Make sure the resize method take effect when doing ajax call Sys.Application.remove_load(resizeElementHeight); Sys.Application.add_load(resizeElementHeight); // Add the loading image. var pageManager = Sys.WebForms.PageRequestManager.getInstance(); pageManager.add_beginRequest(function () { $("#loading").show(); }); pageManager.add_endRequest(function () { $("#loading").hide(); }); } var OnMapCreated = function (map) { map.events.register("mousemove", map, function (e) { var mouseCoordinate = this.getLonLatFromPixel(new OpenLayers.Pixel(e.clientX, e.clientY)); if (mouseCoordinate) { $("#spanMouseCoordinate").text("X:" + mouseCoordinate.lon.toFixed(2) + " Y: " + mouseCoordinate.lat.toFixed(2)); } }); } function displayQueryResult(result) { // Refresh the corresponding Layer var markOverlay = Map1.GetOpenLayersMap().getLayer("QueryResultMarkerOverlay"); markOverlay.redraw(true); // remove all the lines except the header $("#resultTable tr:gt(0)").remove(); // Display data in the Grid table var queryItems = JSON.parse(result); for (var i = 0; i < queryItems.length; i++) { var columns = queryItems[i].values; var featureId = queryItems[i].id; var newRow = $("<tr>"); newRow.append('<td><input type="image" id="' + featureId + '" src="/Images/find.png" onclick="zoomToFeature(this)" /></td>'); newRow.append("<td>" + columns[0].Value + "</td>"); newRow.append("<td>" + columns[2].Value + "</td>"); newRow.append("<td>" + columns[3].Value + "</td>"); newRow.append("<td>" + (columns[4].Value < 0 ? "Unknown" : columns[4].Value) + "</td>"); newRow.append("<td>" + (columns[5].Value < 0 ? "Unknown" : columns[5].Value) + "</td>"); newRow.append("<td>" + columns[1].Value + "</td>"); $("#resultTable > tbody:last").append(newRow); } $("#loading").hide(); } function zoomToFeature(element) { var args = { "command": "ZoomToFeature", "featureId": $(element).attr("id") }; $DoCallback(args, function (result) { if (result) { var map = Map1.GetOpenLayersMap(); map.zoomToExtent(OpenLayers.Geometry.fromWKT(result).getBounds()); } }) } function $DoCallback(arg, callbackEvent, context) { $("#loading").show(); WebForm_DoCallback("__Page", JSON.stringify(arg), callbackEvent, context, null, false); } // Override to support showing the drawing radius of circle var OnMapCreating = function (map) { var msDrawCircleLineId = ""; var msDrawCircleLabelId = ""; OpenLayers.Handler.RegularPolygon.prototype.move = function (evt) { var maploc = this.map.getLonLatFromPixel(evt.xy); var point = new OpenLayers.Geometry.Point(maploc.lon, maploc.lat); if (this.irregular) { var ry = Math.sqrt(2) * Math.abs(point.y - this.origin.y) / 2; this.radius = Math.max(this.map.getResolution() / 2, ry); } else if (this.fixedRadius) { this.origin = point; } else { this.calculateAngle(point, evt); this.radius = Math.max(this.map.getResolution() / 2, point.distanceTo(this.origin)); } this.modifyGeometry(); if (this.irregular) { var dx = point.x - this.origin.x; var dy = point.y - this.origin.y; var ratio; if (dy == 0) { ratio = dx / (this.radius * Math.sqrt(2)); } else { ratio = dx / dy; } this.feature.geometry.resize(1, this.origin, ratio); this.feature.geometry.move(dx / 2, dy / 2); } this.layer.drawFeature(this.feature, this.style); // if it's circle, added the drawing distance and radius if (!this.irregular) { var pointArray = []; pointArray.push(this.origin); pointArray.push(point); if (msDrawCircleLineId != "" && this.layer.getFeatureById(msDrawCircleLineId)) { this.layer.removeFeatures([this.layer.getFeatureById(msDrawCircleLineId)]); } if (msDrawCircleLabelId != "" && this.layer.getFeatureById(msDrawCircleLabelId)) { this.layer.removeFeatures([this.layer.getFeatureById(msDrawCircleLabelId)]); } var radiusLine = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.LineString(pointArray), null, this.style); msDrawCircleLineId = radiusLine.id; this.layer.addFeatures([radiusLine]); var radiusLabelText = ""; var radiusLength = radiusLine.geometry.getGeodesicLength(this.layer.map.getProjectionObject()); var inPerDisplayUnit = OpenLayers.INCHES_PER_UNIT["mi"]; if (inPerDisplayUnit) { var inPerMapUnit = OpenLayers.INCHES_PER_UNIT["m"]; radiusLength *= (inPerMapUnit / inPerDisplayUnit); } radiusLabelText = parseFloat(radiusLength).toFixed(4).toString() + 'mi'; point.distanceTo(this.origin).toString() var radiusLabelFeature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(point.x + 0.1 * this.layer.map.getExtent().getHeight(), point.y - 0.1 * this.layer.map.getExtent().getHeight()), {}, { label: radiusLabelText }); msDrawCircleLabelId = radiusLabelFeature.id; this.layer.addFeatures([radiusLabelFeature]); } } }
using System.Collections.ObjectModel; using System.Runtime.Serialization; namespace ThinkGeo.MapSuite.EarthquakeStatistics { [DataContract] public class CallbackRequest { private string mapType; private string command; private string featureId; private Collection<EarthquakeQueryConfiguration> queryConfigrations; public CallbackRequest() { } [DataMember(Name|= "command")] public string Command { get { return command; } set { command = value; } } [DataMember(Name|= "mapType")] public string MapDisplayType { get { return mapType; } set { mapType = value; } } [DataMember(Name|= "featureId")] public string FeatureId { get { return featureId; } set { featureId = value; } } [DataMember(Name|= "configs")] public Collection<EarthquakeQueryConfiguration> QueryConfigurations { get { if (queryConfigrations == null) { queryConfigrations = new Collection<EarthquakeQueryConfiguration>(); } return queryConfigrations; } internal set { queryConfigrations = value; } } } }
using System; using System.Collections.ObjectModel; using System.Diagnostics; using ThinkGeo.MapSuite.Core; namespace ThinkGeo.MapSuite.EarthquakeStatistics { public class EarthquakeHeatFeatureLayer : FeatureLayer { private HeatLayer heatLayer; public EarthquakeHeatFeatureLayer() : this(null) { } public EarthquakeHeatFeatureLayer(FeatureSource featureSource) : base() { FeatureSource = featureSource; } public new FeatureSource FeatureSource { get { return base.FeatureSource; } set { base.FeatureSource = value; heatLayer = new HeatLayer(value); } } public HeatStyle HeatStyle { get { return heatLayer.HeatStyle; } set { heatLayer.HeatStyle = value; } } protected override void DrawCore(GeoCanvas canvas, Collection<SimpleCandidate> labelsInAllLayers) { try { heatLayer.Draw(canvas, labelsInAllLayers); } catch (Exception ex) { Debug.WriteLine(ex.Message); } } } }
using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using ThinkGeo.MapSuite.Core; using System.Globalization; namespace ThinkGeo.MapSuite.EarthquakeStatistics { public class EarthquakeIsoLineFeatureLayer : FeatureLayer { private DynamicIsoLineLayer isoLineLayer; private Collection<GeoColor> levelAreaColors; private ClassBreakStyle levelClassBreakStyle; public EarthquakeIsoLineFeatureLayer() : this(null) { } public EarthquakeIsoLineFeatureLayer(ShapeFileFeatureSource featureSource) { FeatureSource = featureSource; } public new FeatureSource FeatureSource { get { return base.FeatureSource; } set { base.FeatureSource = value; Initialize(); } } public Collection<double> IsoLineLevels { get { Collection<double> result = null; if (isoLineLayer != null) { result = isoLineLayer.IsoLineLevels; } return result; } } public Collection<GeoColor> LevelAreaColors { get { if (levelAreaColors == null) { levelAreaColors = new Collection<GeoColor>(); levelAreaColors.Add(GeoColor.FromHtml("#ffffbe")); levelAreaColors.Add(GeoColor.FromHtml("#fdff9e")); levelAreaColors.Add(GeoColor.FromHtml("#fdff37")); levelAreaColors.Add(GeoColor.FromHtml("#fdda04")); levelAreaColors.Add(GeoColor.FromHtml("#ffa701")); levelAreaColors.Add(GeoColor.FromHtml("#ff6f02")); levelAreaColors.Add(GeoColor.FromHtml("#ec0000")); levelAreaColors.Add(GeoColor.FromHtml("#b90000")); levelAreaColors.Add(GeoColor.FromHtml("#850100")); levelAreaColors.Add(GeoColor.FromHtml("#620001")); levelAreaColors.Add(GeoColor.FromHtml("#450005")); levelAreaColors.Add(GeoColor.FromHtml("#2b0804")); } return levelAreaColors; } } public ClassBreakStyle LevelClassBreakStyle { get { if (levelClassBreakStyle == null) { levelClassBreakStyle = new ClassBreakStyle(isoLineLayer.DataValueColumnName); Collection<Style> firstStyles = new Collection<Style>(); firstStyles.Add(new AreaStyle(new GeoPen(GeoColor.FromHtml("#fe6b06"), 1), new GeoSolidBrush(new GeoColor(100, LevelAreaColors[0])))); levelClassBreakStyle.ClassBreaks.Add(new ClassBreak(double.MinValue, firstStyles)); for (int i = 0; i < IsoLineLevels.Count - 1; i++) { Collection<Style> styles = new Collection<Style>(); styles.Add(new AreaStyle(new GeoPen(GeoColor.FromHtml("#fe6b06"), 1), new GeoSolidBrush(new GeoColor(100, LevelAreaColors[i|+ 1])))); levelClassBreakStyle.ClassBreaks.Add(new ClassBreak(IsoLineLevels[i|+ 1], styles)); } } return levelClassBreakStyle; } } protected override void DrawCore(GeoCanvas canvas, Collection<SimpleCandidate> labelsInAllLayers) { isoLineLayer.Draw(canvas, labelsInAllLayers); } private void Initialize() { Dictionary<PointShape, double> dataPoints = new Dictionary<PointShape, double>(); if (!FeatureSource.IsOpen) { FeatureSource.Open(); } Collection<Feature> allFeatures = FeatureSource.GetAllFeatures(new Collection<string>() { Resources.LongitudeColumnName, Resources.LatitudeColumnName, Resources.MagnitudeColumnName }); var featureColumnQuery = allFeatures.Where(n => double.Parse(n.ColumnValues[Resources.MagnitudeColumnName]) > 0).Select(n => new { Longitude = double.Parse(n.ColumnValues[Resources.LongitudeColumnName]), Latitude = double.Parse(n.ColumnValues[Resources.LatitudeColumnName]), Magnitude = double.Parse(n.ColumnValues[Resources.MagnitudeColumnName]) }); foreach (var column in featureColumnQuery) { dataPoints.Add(new PointShape(column.Longitude, column.Latitude), column.Magnitude); } double[] dataCollection = dataPoints.Select(n => n.Value).ToArray(); Collection<double> isoLineLevels = new Collection<double>(GetClassBreakValues(dataCollection, 12).ToList()); isoLineLayer = new DynamicIsoLineLayer(dataPoints, isoLineLevels, new InverseDistanceWeightedGridInterpolationModel(3, double.MaxValue), IsoLineType.ClosedLinesAsPolygons); isoLineLayer.CustomStyles.Add(LevelClassBreakStyle); //Create the text styles to label the lines TextStyle textStyle = TextStyles.CreateSimpleTextStyle(isoLineLayer.DataValueColumnName, "Arial", 8, DrawingFontStyles.Bold, GeoColor.StandardColors.Black, 0, 0); textStyle.HaloPen = new GeoPen(GeoColor.StandardColors.White, 2); textStyle.OverlappingRule = LabelOverlappingRule.NoOverlapping; textStyle.SplineType = SplineType.StandardSplining; textStyle.DuplicateRule = LabelDuplicateRule.UnlimitedDuplicateLabels; textStyle.TextLineSegmentRatio = 9999999; textStyle.FittingLineInScreen = true; textStyle.SuppressPartialLabels = true; textStyle.NumericFormat = "{0:0.00}"; isoLineLayer.CustomStyles.Add(textStyle); } private Dictionary<PointShape, double> GetDataPoints() { return (from feature in FeatureSource.GetAllFeatures(GetReturningColumns()) where double.Parse(feature.ColumnValues[Resources.MagnitudeColumnName]) > 0 select new PointShape { X = double.Parse(feature.ColumnValues[Resources.LongitudeColumnName], CultureInfo.InvariantCulture), Y = double.Parse(feature.ColumnValues[Resources.LatitudeColumnName], CultureInfo.InvariantCulture), Z = double.Parse(feature.ColumnValues[Resources.MagnitudeColumnName], CultureInfo.InvariantCulture) }).ToDictionary(point => point, point => point.Z); } private static Collection<double> GetClassBreakValues(IEnumerable<double> values, int count) { Collection<double> result = new Collection<double>(); double[] sortedValues = values.OrderBy(v => v).ToArray(); int classCount = sortedValues.Length / count; for (var i = 1; i < count; i++) { result.Add(sortedValues[i|* classCount]); } return result; } private static IEnumerable<string> GetReturningColumns() { yield return Resources.LongitudeColumnName; yield return Resources.LatitudeColumnName; yield return Resources.MagnitudeColumnName; } } }
using System.Runtime.Serialization; namespace ThinkGeo.MapSuite.EarthquakeStatistics { [DataContract] public class EarthquakeQueryConfiguration { private string parameter; private int minimum; private int maximum; public EarthquakeQueryConfiguration() { } [DataMember(Name|= "name")] public string Parameter { get { return parameter; } set { parameter = value; } } [DataMember(Name|= "min")] public int Minimum { get { return minimum; } set { minimum = value; } } [DataMember(Name|= "max")] public int Maximum { get { return maximum; } set { maximum = value; } } } }
using System.Collections.Generic; using System.Runtime.Serialization; using ThinkGeo.MapSuite.Core; namespace ThinkGeo.MapSuite.EarthquakeStatistics { [DataContract] public class JsonFeature { private string id; private string wkt; private Dictionary<string, string> values; public JsonFeature() { } public JsonFeature(Feature feature) : this(feature.Id, feature.GetWellKnownText(), feature.ColumnValues) { } public JsonFeature(string id, string wkt, Dictionary<string, string> values) { this.id = id; this.wkt = wkt; this.values = values; } [DataMember(Name|= "id")] public string Id { get { return id; } set { id = value; } } [DataMember(Name|= "wkt")] public string Wkt { get { return wkt; } set { wkt = value; } } [DataMember(Name|= "values")] public Dictionary<string, string> Values { get { return values; } set { values = value; } } } }
using System.Collections.Generic; using System.Collections.ObjectModel; using System.Data; using ThinkGeo.MapSuite.Core; namespace ThinkGeo.MapSuite.EarthquakeStatistics { public static class InternalHelper { public static DataTable GetQueriedResultTableDefination() { DataTable tableDefination = new DataTable(); tableDefination.Columns.Add("id"); tableDefination.Columns.Add("year"); tableDefination.Columns.Add("longitude"); tableDefination.Columns.Add("latitude"); tableDefination.Columns.Add("depth_km"); tableDefination.Columns.Add("magnitude"); tableDefination.Columns.Add("location"); return tableDefination; } public static string ConvertFeaturesToJson(IEnumerable<Feature> features) { Collection<JsonFeature> jsonFeatures = new Collection<JsonFeature>(); foreach (Feature feature in features) { // re-order the columns for display it in query table Dictionary<string, string> orderedColumns = new Dictionary<string, string>(); orderedColumns.Add("year", feature.ColumnValues["YEAR"]); orderedColumns.Add("longitude", feature.ColumnValues["LONGITUDE"]); orderedColumns.Add("latitude", feature.ColumnValues["LATITIUDE"]); orderedColumns.Add("depth_km", feature.ColumnValues["DEPTH_KM"]); orderedColumns.Add("magnitude", feature.ColumnValues["magnitude"]); orderedColumns.Add("location", feature.ColumnValues["LOCATION"]); JsonFeature jsonFeature = new JsonFeature(feature.Id, feature.GetWellKnownText(), orderedColumns); jsonFeatures.Add(new JsonFeature(feature)); } return JsonSerializer.Serialize<Collection<JsonFeature>>(jsonFeatures); } } }
using System; using System.IO; using System.Runtime.Serialization.Json; using System.Text; namespace ThinkGeo.MapSuite.EarthquakeStatistics { /// <summary> /// Helper class to serialize or deserialize a generic object to/from JSON. /// </summary> public class JsonSerializer { /// <summary> /// Serializes an object to JSON /// </summary> /// <typeparam name="T">Type of object to serialize</typeparam> /// <param name="obj">Instance of object to serialize</param> /// <returns>JSON string</returns> public static string Serialize<T>(T obj) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType()); MemoryStream ms = new MemoryStream(); serializer.WriteObject(ms, obj); string retVal = Encoding.Default.GetString(ms.ToArray()); ms.Dispose(); return retVal; } /// <summary> /// Deserialize an object from JSON /// </summary> /// <typeparam name="T">Type of object to deserialize</typeparam> /// <param name="json">JSON string to deserialize</param> /// <returns>deserialized object</returns> public static T Deserialize<T>(string json) { T obj = Activator.CreateInstance<T>(); MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)); DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType()); obj = (T)serializer.ReadObject(ms); ms.Close(); ms.Dispose(); return obj; } } }