User Tools

Site Tools


source_code_mvcedition_projecttemplates_usearthquakestatics_cs.zip

Source Code MvcEdition ProjectTemplates USEarthquakeStatics CS.zip

DefaultController.cs

using System;
using System.Collections.ObjectModel;
using System.Web.Mvc;
using ThinkGeo.MapSuite.Core;
using ThinkGeo.MapSuite.EarthquakeStatistics;
using ThinkGeo.MapSuite.MvcEdition;
using System.Linq;
using System.Collections.Generic;
using System.Configuration;
namespace ThinkGeo.MapSuite.EarthquakeStatistics.Controllers
{
    public class DefaultController : Controller
    {
        public ActionResult Index()
        {
            // Initialize map for the page
            Map map = InitializeMap();
            return View(map);
        }
        [MapActionFilter]
        public void SetDrawMode(Map map, GeoCollection<object> args)
        {
            switch (args[0].ToString())
            {
                case "DrawCircle":
                    map.EditOverlay.TrackMode = TrackMode.Circle;
                    break;
                case "DrawRectangle":
                    map.EditOverlay.TrackMode = TrackMode.Rectangle;
                    break;
                case "DrawPolygon":
                    map.EditOverlay.TrackMode = TrackMode.Polygon;
                    break;
                case "ClearAll":
                    ClearAllShapesOnMap(map);
                    break;
                case "Pan":
                default:
                    map.EditOverlay.TrackMode = TrackMode.None;
                    break;
            }
        }
        [MapActionFilter]
        public string GetQueryingFeatures(Map map, GeoCollection<object> args)
        {
            string featuresInJson = string.Empty;
            if (map != null)
            {
                Collection<EarthquakeQueryConfiguration> configurations = JsonSerializer.Deserialize<Collection<EarthquakeQueryConfiguration>>(args[0].ToString());
                Collection<Feature> selectedFeatures = FilterEarthquakePoints(map, configurations);
                featuresInJson = InternalHelper.ConvertFeaturesToJson(selectedFeatures);
                Session["QueryConfiguration"] = configurations;
            }
            return featuresInJson;
        }
        [MapActionFilter]
        public string GetTrackFeatures(Map map, GeoCollection<object> args)
        {
            string featuresInJson = string.Empty;
            if (map != null)
            {
                // convert wkt to thinkgeo features
                Feature[] trackedFeatrues = args.Select((t) =>
                {
                    return new Feature(t.ToString());
                }).OfType<Feature>().ToArray();
                // add those features into edit overlay
                map.EditOverlay.Features.Clear();
                foreach (Feature item in trackedFeatrues)
                {
                    map.EditOverlay.Features.Add(item);
                }
                // restore other query conditions from session.
                Collection<EarthquakeQueryConfiguration> queryConfigurations = new Collection<EarthquakeQueryConfiguration>();
                if (Session["QueryConfiguration"] != null)
                {
                    queryConfigurations = Session["QueryConfiguration"] as Collection<EarthquakeQueryConfiguration>;
                }
                Collection<Feature> selectedFeatures = FilterEarthquakePoints(map, queryConfigurations);
                featuresInJson = InternalHelper.ConvertFeaturesToJson(selectedFeatures);
            }
            return featuresInJson;
        }
        [MapActionFilter]
        public void SwitchMapType(Map map, GeoCollection<object> args)
        {
            if (map != null)
            {
                string mapType = args[0].ToString();
                LayerOverlay earthquakeOverlay = map.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"))
                {
                    map.AdornmentOverlay.Layers["IsoLineLevelLegendLayer"].IsVisible = true;
                }
                else
                {
                    map.AdornmentOverlay.Layers["IsoLineLevelLegendLayer"].IsVisible = false;
                }
            }
        }
        [MapActionFilter]
        public string ZoomToFeature(Map map, GeoCollection<object> args)
        {
            string identifiedFeatureBbox = string.Empty;
            if (map != null)
            {
                string featureId = args[0].ToString();
                LayerOverlay queryResultMarkerOverlay = map.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;
                map.ZoomTo(center, map.ZoomLevelSet.GetZoomLevels()[16].Scale);
                queryResultMarkerOverlay.Redraw();
                identifiedFeatureBbox = currentFeature.GetBoundingBox().GetWellKnownText();
            }
            return identifiedFeatureBbox;
        }
        private void ClearAllShapesOnMap(Map Map1)
        {
            // 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 Map InitializeMap()
        {
            Map Map1 = new Map("Map1");
            Map1.Width = new System.Web.UI.WebControls.Unit(100, System.Web.UI.WebControls.UnitType.Percentage);
            Map1.Height = new System.Web.UI.WebControls.Unit(100, System.Web.UI.WebControls.UnitType.Percentage);
            Map1.MapUnit = GeographyUnit.Meter;
            Map1.MapTools.OverlaySwitcher.Enabled = true;
            Map1.MapTools.OverlaySwitcher.BaseOverlayTitle = " ";
            // add base layers.
            AddBaseMapLayers(Map1);
            // add the earthquake layer to as the data source.
            AddEarthquakeLayers(Map1);
            // add query shape layers, like track layer, marker layer and highlight layer etc.
            AddQueryResultLayers(Map1);
            // add adorment layers
            AddAdormentLayers(Map1);
            Map1.CurrentExtent = new RectangleShape(-14503631.6805645, 7498410.41581975, -7928840.70035357, 4171879.26511785);
            Map1.OnClientTrackShapeFinished = "trackShapeFinished";
            return Map1;
        }
        private void AddBaseMapLayers(Map Map1)
        {
            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(Map Map1)
        {
            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(Map Map1)
        {
            // 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(Map Map1)
        {
            // ScaleBar
            ScaleBarAdornmentLayer scaleBarAdormentLayer = new ScaleBarAdornmentLayer();
            scaleBarAdormentLayer.XOffsetInPixel = 10;
            scaleBarAdormentLayer.XOffsetInPixel = 5;
            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].DefaultAreaStyle;
                legendItem.ImageWidth = 25;
                isoLevelLegendLayer.LegendItems.Add(legendItem);
            }
            Map1.AdornmentOverlay.Layers.Add("IsoLineLevelLegendLayer", isoLevelLegendLayer);
        }
        private Collection<Feature> FilterEarthquakePoints(Map Map1, 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());
        }
    }
}

EarthquakeHeatFeatureLayer.cs

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);
            }
        }
    }
}

EarthquakeIsoLineFeatureLayer.cs

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 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 { return isoLineLayer.IsoLineLevels; }
        }
        public ClassBreakStyle LevelClassBreakStyle
        {
            get { return levelClassBreakStyle; }
        }
        protected override void DrawCore(GeoCanvas canvas, Collection<SimpleCandidate> labelsInAllLayers)
        {
            isoLineLayer.Draw(canvas, labelsInAllLayers);
        }
        private void Initialize()
        {
            Collection<GeoColor> 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"));
            FeatureSource.Open();
            Dictionary<PointShape, double> dataPoints = GetDataPoints();
            GridInterpolationModel interpolationModel = new InverseDistanceWeightedGridInterpolationModel(3, double.MaxValue);
            isoLineLayer = new DynamicIsoLineLayer(dataPoints, GetClassBreakValues(dataPoints.Values, 12), interpolationModel, IsoLineType.ClosedLinesAsPolygons);
            levelClassBreakStyle = new ClassBreakStyle(isoLineLayer.DataValueColumnName);
            levelClassBreakStyle.ClassBreaks.Add(new ClassBreak(double.MinValue, new AreaStyle(new GeoPen(GeoColor.FromHtml("#FE6B06"), 1), new GeoSolidBrush(new GeoColor(100, levelAreaColors[0])))));
            for (int i = 0; i < IsoLineLevels.Count - 1; i++)
            {
                levelClassBreakStyle.ClassBreaks.Add(new ClassBreak(IsoLineLevels[i|+ 1], new AreaStyle(new GeoPen(GeoColor.FromHtml("#FE6B06"), 1), new GeoSolidBrush(new GeoColor(100, levelAreaColors[i|+ 1])))));
            }
            isoLineLayer.CustomStyles.Add(levelClassBreakStyle);
            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["MAGNITUDE"]) > 0
                    select new PointShape
                    {
                        X = double.Parse(feature.ColumnValues["LONGITUDE"], CultureInfo.InvariantCulture),
                        Y = double.Parse(feature.ColumnValues["LATITIUDE"], CultureInfo.InvariantCulture),
                        Z = double.Parse(feature.ColumnValues["MAGNITUDE"], 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 "LONGITUDE";
            yield return "LATITIUDE";
            yield return "MAGNITUDE";
        }
    }
}

ready-functions.js

$(document).ready(function () {
    initializePageElements();
    // Map display type
    $("#divBasemaps input[type='image']").bind("click", function () {
        Map1.ajaxCallAction("default", "SwitchMapType", { command: $(this).attr("command") }, function () {
            Map1.getAdornmentOverlay().redraw(true);
            Map1.getLayer("EarthquakeOverlay").redraw(true);
        });
    });
    $("#btnPanMap").bind("click", function () {
        $("#divTrackShapes input[type=image]").not($(this)).removeClass("active");
    });
    $("#btnClearAll").bind("click", function () {
        $("#divTrackShapes input[type=image]").not($("#btnPanMap")).removeClass("active");
        $("#btnPanMap").addClass("active");
        Map1.setDrawMode("Normal");
        Map1.getEditOverlay().removeAllFeatures();
        Map1.ajaxCallAction("default", "SetDrawMode", { command: "ClearAll" }, function () {
            Map1.getLayer('EarthquakeOverlay').redraw(true);
            Map1.getLayer('TrackShapeOverlay').redraw(true);
            Map1.getLayer('QueryResultMarkerOverlay').redraw(true);
            $("#resultTable tr:gt(0)").remove();
        });
    });
    // Configuration slider
    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);
        $("#loading").show();
        Map1.ajaxCallAction("default", "GetQueryingFeatures", { "configs": JSON.stringify(queryItems) }, 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: 2012,
        values: [1568,|2012],
        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.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();
    });
}
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.get_responseData());
    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="/Content/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) {
    Map1.ajaxCallAction("default", "ZoomToFeature", { featureId: $(element).attr("id") }, function (result) {
        if (result.get_responseData()) {
            var wkt = result.get_responseData();
            var bbox = OpenLayers.Geometry.fromWKT(wkt).getBounds();
            Map1.zoomToExtent(bbox);
        }
    });
}
function trackShapeFinished(e) {
    var features = JSON.parse(e.features);
    var wkts = [];
    for (var i = 0; i < features.length; i++) {
        wkts.push(features[i].wkt);
    }
    $("#loading").show();
    Map1.ajaxCallAction("default", "GetTrackFeatures", wkts, displayQueryResult);
}
// 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]);
        }
    }
}

EarthquakeQueryConfiguration.cs

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; }
        }
    }
}

JsonFeature.cs

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; }
        }
    }
}

InternalHelper.cs

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);
        }
    }
}

InternalHelper.cs

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;
        }
    }
}

Index.cshtml

@using ThinkGeo.MapSuite.Core
@using ThinkGeo.MapSuite.MvcEdition
@using ThinkGeo.MapSuite.EarthquakeStatistics
@model ThinkGeo.MapSuite.MvcEdition.Map
@{
    ViewBag.Title = "US Earthquake Statistics";
}
<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">
                    <input type="image" id="btnHeatMap" src="@Url.Content("~/Content/Images/heatMap.png")" command="Heat Map" />
                    <input type="image" id="btnPointMap" src="@Url.Content("~/Content/Images/pointMap.png")" command="Regular Point Map" />
                    <input type="image" id="btnIsolineMap" src="@Url.Content("~/Content/Images/Isoline.png")" command="IsoLines Map" />
                </div>
                <div id="divblueBanner">
                    Earthquake Information Explorer
                </div>
                <h4>
                    Query Tool:</h4>
                <div id="divTrackShapes" class="divBorder">
                    <input type="image" id="btnPanMap" title="Pan the map" src="@Url.Content("~/Content/Images/Pan.png")" class="active" onclick="Map1.setDrawMode('normal');" />
                    <input type="image" id="btnDrawPolygon" title="Draw a polygon" src="@Url.Content("~/Content/Images/DrawPolygon.png")" onclick="Map1.setDrawMode('Polygon');" />
                    <input type="image" id="btnDrawRectangle" title="Draw a rectangle" src="@Url.Content("~/Content/Images/DrawRectangle.png")" onclick="Map1.setDrawMode('Rectangle');"/>
                    <input type="image" id="btnDrawCircle" title="Draw a circle" src="@Url.Content("~/Content/Images/Drawcircle.png")" onclick="Map1.setDrawMode('Circle');"/>
                    <input type="image" id="btnClearAll" title="Clear all" src="@Url.Content("~/Content/Images/clear.png")" command="ClearAll"/>
                </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 alt="collapse" id="collapse" src="@Url.Content("~/Content/Images/collapse.gif")" />
        </div>
        <div id="map-content">
            <div id="mapContainer">
                @{
                    Html.ThinkGeo().Map(Model).Render();
                }
            </div>
            <div id="resultContainer">
                <div class="grid-contianer">
                    <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>
                    </table>
                </div>
            </div>
        </div>
    </div>
    <div id="footer">
        <span id="spanMouseCoordinate"></span>
    </div>
</div>
<div id="loading">
    <img id="loading-image" src="@Url.Content("Content/Images/loading.gif")" alt="Loading..." />
</div>
source_code_mvcedition_projecttemplates_usearthquakestatics_cs.zip.txt · Last modified: 2015/09/09 03:33 by admin