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
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace ThinkGeo.MapSuite.EarthquakeStatistics { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Configuration; using System.Drawing; using System.Drawing.Drawing2D; using System.Globalization; using System.IO; using System.Linq; using System.Windows.Forms; using ThinkGeo.MapSuite.Core; using ThinkGeo.MapSuite.DesktopEdition; using ThinkGeo.MapSuite.EarthquakeStatistics.Properties; namespace ThinkGeo.MapSuite.EarthquakeStatistics { public partial class MainForm : Form { private static readonly RectangleShape defaultExtent = new RectangleShape(-19062735.6816748, 9273256.52450252, -5746827.16371793, 2673516.56066139); private OverlaySwitcher switcher; private FeatureLayer activeStyleLayer; private InMemoryFeatureLayer markerMemoryLayer; private Collection<EarthquakeItem> earthquakeItems; private InMemoryFeatureLayer markerMemoryHighlightLayer; public MainForm() { InitializeComponent(); InitializeToolTips(); InitializeBackground(); earthquakeItems = new Collection<EarthquakeItem>(); } private void MainForm_Load(object sender, EventArgs e) { InitializeMap(); InitializeOverlaySwitcher(); PanRadioButton.Checked = true; HeatMapRadioButton.Checked = true; } private void InitializeMap() { map.MapUnit = GeographyUnit.Meter; map.AdornmentOverlay.ShowLogo = false; map.CurrentExtent = defaultExtent; ScaleBarAdornmentLayer scaleBarAdormentLayer = new ScaleBarAdornmentLayer(); scaleBarAdormentLayer.UnitFamily = UnitSystem.Imperial; map.AdornmentOverlay.Layers.Add(scaleBarAdormentLayer); RadiusMearsureTrackInteractiveOverlay trackOverlay = new RadiusMearsureTrackInteractiveOverlay(DistanceUnit.Mile, map.MapUnit); trackOverlay.TrackEnded += TrackOverlay_TrackEnded; map.TrackOverlay = trackOverlay; InitializeOverlays(); map.Refresh(); } private void InitializeOverlays() { string cacheFolder = Path.Combine(Path.GetTempPath(), "TileCache"); WorldMapKitWmsDesktopOverlay worldMapKitOverlay = new WorldMapKitWmsDesktopOverlay(); worldMapKitOverlay.Name = Resources.WorldMapKitOverlayName; worldMapKitOverlay.Projection = WorldMapKitProjection.SphericalMercator; worldMapKitOverlay.IsVisible = true; worldMapKitOverlay.TileCache = new FileBitmapTileCache(cacheFolder, Resources.WorldMapKitKey); map.Overlays.Add(Resources.WorldMapKitKey, worldMapKitOverlay); OpenStreetMapOverlay openStreetMapOverlay = new OpenStreetMapOverlay(); openStreetMapOverlay.Name = Resources.OSMOverlayName; openStreetMapOverlay.IsVisible = false; openStreetMapOverlay.TileCache = new FileBitmapTileCache(cacheFolder, Resources.OpenStreetMapKey); map.Overlays.Add(Resources.OpenStreetMapKey, openStreetMapOverlay); BingMapsOverlay bingMapsAerialOverlay = new BingMapsOverlay(); bingMapsAerialOverlay.Name = Resources.BingMapsAerialOverlayName; bingMapsAerialOverlay.MapType = BingMapsMapType.Aerial; bingMapsAerialOverlay.IsVisible = false; bingMapsAerialOverlay.TileCache = new FileBitmapTileCache(cacheFolder, Resources.BingMapsAerial); map.Overlays.Add(Resources.BingMapsAerial, bingMapsAerialOverlay); BingMapsOverlay bingMapsRoadOverlay = new BingMapsOverlay(); bingMapsRoadOverlay.Name = Resources.BingMapsRoadOverlayName; bingMapsRoadOverlay.MapType = BingMapsMapType.Road; bingMapsRoadOverlay.IsVisible = false; bingMapsRoadOverlay.TileCache = new FileBitmapTileCache(cacheFolder, Resources.BingMapsRoad); map.Overlays.Add(Resources.BingMapsRoad, bingMapsRoadOverlay); LayerOverlay styleLayersOverLay = new LayerOverlay(); map.Overlays.Add(Resources.StyleLayerOverLayKey, styleLayersOverLay); ManagedProj4Projection wgs84ToMercatorProjection = new ManagedProj4Projection(); wgs84ToMercatorProjection.InternalProjectionParametersString = ManagedProj4Projection.GetDecimalDegreesParametersString(); wgs84ToMercatorProjection.ExternalProjectionParametersString = ManagedProj4Projection.GetSphericalMercatorParametersString(); EarthquakeHeatFeatureLayer heatLayer = new EarthquakeHeatFeatureLayer(new ShapeFileFeatureSource(ConfigurationManager.AppSettings["DataShapefileFileName"])); heatLayer.IsVisible = false; heatLayer.HeatStyle = new HeatStyle(10, 100, Resources.MagnitudeColumnName, 0, 12, 100, DistanceUnit.Kilometer); heatLayer.FeatureSource.Projection = wgs84ToMercatorProjection; heatLayer.Name = Resources.HeatStyleLayerName; styleLayersOverLay.Layers.Add(heatLayer); ShapeFileFeatureLayer pointLayer = new ShapeFileFeatureLayer(ConfigurationManager.AppSettings["DataShapefileFileName"]); pointLayer.IsVisible = false; pointLayer.FeatureSource.Projection = wgs84ToMercatorProjection; pointLayer.Name = Resources.PointStyleLayerName; pointLayer.ZoomLevelSet.ZoomLevel01.DefaultPointStyle = PointStyles.CreateSimpleCircleStyle(GeoColor.StandardColors.Red, 6, GeoColor.StandardColors.White, 1); pointLayer.ZoomLevelSet.ZoomLevel01.ApplyUntilZoomLevel = ApplyUntilZoomLevel.Level20; styleLayersOverLay.Layers.Add(pointLayer); FeatureSource isoLineFeatureSource = new ShapeFileFeatureSource(ConfigurationManager.AppSettings["DataShapefileFileName"]); EarthquakeIsoLineFeatureLayer isoLineLayer = new EarthquakeIsoLineFeatureLayer(isoLineFeatureSource); isoLineLayer.IsVisible = false; isoLineLayer.FeatureSource.Projection = wgs84ToMercatorProjection; isoLineLayer.Name = Resources.IsolineStyleLayerName; styleLayersOverLay.Layers.Add(isoLineLayer); LayerOverlay queryResultMarkerOverlay = new LayerOverlay(); map.Overlays.Add("QueryResultMarkerOverlay", queryResultMarkerOverlay); 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)); markerMemoryLayer = new InMemoryFeatureLayer(); markerMemoryLayer.ZoomLevelSet.ZoomLevel01.DefaultPointStyle = PointStyles.CreateSimpleCircleStyle(GeoColor.SimpleColors.Orange, 8, GeoColor.SimpleColors.White, 1); markerMemoryLayer.ZoomLevelSet.ZoomLevel01.ApplyUntilZoomLevel = ApplyUntilZoomLevel.Level20; queryResultMarkerOverlay.Layers.Add(markerMemoryLayer); markerMemoryHighlightLayer = new InMemoryFeatureLayer(); markerMemoryHighlightLayer.ZoomLevelSet.ZoomLevel01.DefaultPointStyle = highlightStyle; markerMemoryHighlightLayer.ZoomLevelSet.ZoomLevel01.ApplyUntilZoomLevel = ApplyUntilZoomLevel.Level20; queryResultMarkerOverlay.Layers.Add(markerMemoryHighlightLayer); } private void InitializeOverlaySwitcher() { Collection<Overlay> baseOverlays = new Collection<Overlay>(); baseOverlays.Add(map.Overlays[Resources.WorldMapKitKey]); baseOverlays.Add(map.Overlays[Resources.OpenStreetMapKey]); baseOverlays.Add(map.Overlays[Resources.BingMapsAerial]); baseOverlays.Add(map.Overlays[Resources.BingMapsRoad]); switcher = new OverlaySwitcher(baseOverlays, map); switcher.Anchor = AnchorStyles.Right | AnchorStyles.Top; switcher.Location = new Point(Width - 208, 65); switcher.Size = new Size(185, 90); Controls.Add(switcher); switcher.BringToFront(); switcher.Refresh(); switcher.OverlayChanged += OverlaySwitcher_OverlayChanged; PictureBox overlayPictureBox = new PictureBox(); overlayPictureBox.Anchor = AnchorStyles.Right | AnchorStyles.Top; overlayPictureBox.Image = Resources.switcher_minimize; overlayPictureBox.SizeMode = PictureBoxSizeMode.AutoSize; overlayPictureBox.Location = new Point(switcher.Location.X + switcher.Width - overlayPictureBox.Width - 8, switcher.Location.Y + 5); overlayPictureBox.Click += OverlaySwitcherPictureBox_Click; Controls.Add(overlayPictureBox); overlayPictureBox.BringToFront(); } private void TrackOverlay_TrackEnded(object sender, TrackEndedTrackInteractiveOverlayEventArgs e) { Feature queryFeature = UnionTrackedShapes(); if (queryFeature == null) return; activeStyleLayer.FeatureSource.Open(); Collection<Feature> features = activeStyleLayer.FeatureSource.GetFeaturesWithinDistanceOf(queryFeature, map.MapUnit, DistanceUnit.Meter, 0.0001, ReturningColumnsType.AllColumns); earthquakeItems.Clear(); foreach (Feature feature in features) { earthquakeItems.Add(new EarthquakeItem(feature)); } FilterEarthquake(); } private Feature UnionTrackedShapes() { try { Feature[] allPolygonFeatures = map.TrackOverlay.TrackShapeLayer.InternalFeatures.Where(f => f.GetShape() is PolygonShape).ToArray(); return SqlTypesGeometryHelper.Union(allPolygonFeatures); } catch { return null; } } private void FilterEarthquake() { QueryResultItemsDataGridView.Rows.Clear(); ManagedProj4Projection mercatorToWgs84Projection = new ManagedProj4Projection(); mercatorToWgs84Projection.InternalProjectionParametersString = ManagedProj4Projection.GetSphericalMercatorParametersString(); mercatorToWgs84Projection.ExternalProjectionParametersString = ManagedProj4Projection.GetDecimalDegreesParametersString(); mercatorToWgs84Projection.Open(); Collection<EarthquakeItem> items = new Collection<EarthquakeItem>(); for (int i = earthquakeItems.Count - 1; i >= 0; i--) { EarthquakeItem resultItem = earthquakeItems[i]; double latitude, longitude; if (double.TryParse(resultItem.LatitudeCell.Value.ToString(), out latitude) && double.TryParse(resultItem.LongitudeCell.Value.ToString(), out longitude)) { PointShape point = new PointShape(longitude, latitude); point = (PointShape)mercatorToWgs84Projection.ConvertToExternalProjection(point); EarthquakeItem newResultItem = new EarthquakeItem(resultItem.EpicenterFeature); newResultItem.LatitudeCell = new DataGridViewTextBoxCell { Value = point.Y.ToString("f3") }; newResultItem.LongitudeCell = new DataGridViewTextBoxCell { Value = point.X.ToString("f3") }; double year, depth, magnitude; double.TryParse(newResultItem.MagnitudeCell.Value.ToString(), out magnitude); double.TryParse(newResultItem.DepthInKilometerCell.Value.ToString(), out depth); double.TryParse(newResultItem.YearCell.Value.ToString(), out year); if ((magnitude >= MagnitudeSelectionRangeSlider.ValueLeft && magnitude <= MagnitudeSelectionRangeSlider.ValueRight || newResultItem.MagnitudeCell.Value.ToString() == Resources.UnknownString) && (depth <= DepthSelectionRangeSlider.ValueRight && depth >= DepthSelectionRangeSlider.ValueLeft || newResultItem.DepthInKilometerCell.Value.ToString() == Resources.UnknownString) && (year >= DateSelectionRangeSlider.ValueLeft && year <= DateSelectionRangeSlider.ValueRight) || newResultItem.YearCell.Value.ToString() == Resources.UnknownString) { DataGridViewRow newRow = new DataGridViewRow(); newRow.Cells.Add(newResultItem.ImageButtonCell); newRow.Cells.Add(newResultItem.YearCell); newRow.Cells.Add(newResultItem.LongitudeCell); newRow.Cells.Add(newResultItem.LatitudeCell); newRow.Cells.Add(newResultItem.DepthInKilometerCell); newRow.Cells.Add(newResultItem.MagnitudeCell); newRow.Cells.Add(newResultItem.LocationPointCell); QueryResultItemsDataGridView.Rows.Add(newRow); items.Add(newResultItem); } } } mercatorToWgs84Projection.Close(); RefreshMarkersByFeatures(items.Select(f => f.EpicenterFeature)); } private void MapType_CheckedChanged(object sender, EventArgs e) { LayerOverlay styleLayerOverlay = (LayerOverlay)map.Overlays[Resources.StyleLayerOverLayKey]; foreach (Layer layer in styleLayerOverlay.Layers) { layer.IsVisible = false; } RadioButton currentRadioButton = (RadioButton)sender; string layerName = currentRadioButton.Tag.ToString(); FeatureLayer currentLayer = styleLayerOverlay.Layers.OfType<FeatureLayer>().FirstOrDefault(l => l.Name == layerName); if (currentLayer != null) { activeStyleLayer = currentLayer; activeStyleLayer.IsVisible = true; SetEarthquakeLegendsVisible(activeStyleLayer); map.Refresh(styleLayerOverlay); map.Refresh(map.AdornmentOverlay); } } private void SetEarthquakeLegendsVisible(Layer currentLayer) { EarthquakeIsoLineFeatureLayer earthquakeFeatureLayer = currentLayer as EarthquakeIsoLineFeatureLayer; LegendAdornmentLayer earthquakeLegendLayer = GetEarthquakeLegendLayer(earthquakeFeatureLayer); if (earthquakeLegendLayer != null) { earthquakeLegendLayer.IsVisible = earthquakeFeatureLayer != null; } } private LegendAdornmentLayer GetEarthquakeLegendLayer(EarthquakeIsoLineFeatureLayer earthquakeFeatureLayer) { LegendAdornmentLayer isoLevelLegendLayer = null; if (map.AdornmentOverlay.Layers.Contains(Resources.IsoLineLevelLegendLayerName)) { isoLevelLegendLayer = (LegendAdornmentLayer)map.AdornmentOverlay.Layers[Resources.IsoLineLevelLegendLayerName]; } else if (earthquakeFeatureLayer != null) { isoLevelLegendLayer = new LegendAdornmentLayer(); isoLevelLegendLayer.Width = 85; isoLevelLegendLayer.Height = 320; isoLevelLegendLayer.Location = AdornmentLocation.LowerRight; isoLevelLegendLayer.ContentResizeMode = LegendContentResizeMode.Fixed; LegendItem flagLegendItem = new LegendItem(); flagLegendItem.TextStyle = new TextStyle("Magnitude", new GeoFont("Arial", 10), new GeoSolidBrush(GeoColor.StandardColors.Black)); flagLegendItem.TextLeftPadding = -20; isoLevelLegendLayer.LegendItems.Add(flagLegendItem); map.AdornmentOverlay.Layers.Add(Resources.IsoLineLevelLegendLayerName, isoLevelLegendLayer); for (int index = 0; index < earthquakeFeatureLayer.IsoLineLevels.Count; index++) { LegendItem legendItem = new LegendItem(); legendItem.TextStyle = new TextStyle(earthquakeFeatureLayer.IsoLineLevels[index].ToString("f2"), new GeoFont("Arial", 10), new GeoSolidBrush(GeoColor.StandardColors.Black)); legendItem.ImageStyle = earthquakeFeatureLayer.LevelClassBreakStyle.ClassBreaks[index].DefaultAreaStyle; legendItem.ImageWidth = 25; isoLevelLegendLayer.LegendItems.Add(legendItem); } } return isoLevelLegendLayer; } private void MagnitudeSelectionRangeSlider_ValueChanged(object sender, EventArgs e) { MagnitudeLowerLabel.Text = MagnitudeSelectionRangeSlider.ValueLeft.ToString(CultureInfo.InvariantCulture); MagnitudeUpperLabel.Text = MagnitudeSelectionRangeSlider.ValueRight.ToString(CultureInfo.InvariantCulture); } private void DateSelectionRangeSlider_ValueChanged(object sender, EventArgs e) { DateLowerLabel.Text = DateSelectionRangeSlider.ValueLeft.ToString(CultureInfo.InvariantCulture); DateUpperLabel.Text = DateSelectionRangeSlider.ValueRight.ToString(CultureInfo.InvariantCulture); } private void DepthSelectionRangeSlider_ValueChanged(object sender, EventArgs e) { DepthLowerLabel.Text = DepthSelectionRangeSlider.ValueLeft.ToString(CultureInfo.InvariantCulture); DepthUpperLabel.Text = DepthSelectionRangeSlider.ValueRight.ToString(CultureInfo.InvariantCulture); } private void MapModeRadioButton_CheckedChanged(object sender, EventArgs e) { RadioButton radioButton = (RadioButton)sender; if (radioButton != null) { radioButton.FlatAppearance.BorderColor = radioButton.Checked ? Color.FromArgb(136, 136, 136) : Color.White; if (radioButton.Checked) { if (radioButton.Equals(PanRadioButton)) { map.TrackOverlay.TrackMode = TrackMode.None; } else if (radioButton.Equals(rbtnDrawPolygon)) { map.TrackOverlay.TrackMode = TrackMode.Polygon; } else if (radioButton.Equals(rbtnDrawRectangle)) { map.TrackOverlay.TrackMode = TrackMode.Rectangle; } else if (radioButton.Equals(rbtnDrawCircle)) { map.TrackOverlay.TrackMode = TrackMode.Circle; } } } } private void ConfigurationSlider_MouseUp(object sender, MouseEventArgs e) { FilterEarthquake(); } private void ClearTrackResult_Click(object sender, EventArgs e) { PanRadioButton.Checked = true; map.TrackOverlay.TrackShapeLayer.InternalFeatures.Clear(); markerMemoryLayer.InternalFeatures.Clear(); markerMemoryHighlightLayer.InternalFeatures.Clear(); map.Refresh(map.TrackOverlay); map.Refresh(map.Overlays["QueryResultMarkerOverlay"]); earthquakeItems.Clear(); QueryResultItemsDataGridView.Rows.Clear(); } private void OverlaySwitcher_OverlayChanged(object sender, OverlayChangedOverlaySwitcherEventArgs e) { BingMapsOverlay bingMapsOverlay = e.Overlay as BingMapsOverlay; if (bingMapsOverlay != null) { e.Cancel = ApplyBingMapsKey(); } } private bool ApplyBingMapsKey() { bool cancel = false; string bingMapsKey = MapSuiteSampleHelper.GetBingMapsKey(); if (!string.IsNullOrEmpty(bingMapsKey)) { foreach (BingMapsOverlay bingOverlay in map.Overlays.OfType<BingMapsOverlay>()) { bingOverlay.ApplicationId = bingMapsKey; } } else { cancel = true; } return cancel; } private void QueryResultItemsDataGridView_CellClick(object sender, DataGridViewCellEventArgs e) { if (e.ColumnIndex == 0 && e.RowIndex > -1) { DataGridViewCell cell = QueryResultItemsDataGridView.Rows[e.RowIndex].Cells["cluLocation"]; if (cell.Value != null) { map.CurrentExtent = BaseShape.CreateShapeFromWellKnownData((string)cell.Value).GetBoundingBox(); map.Refresh(); } } } private void QueryResultItemsDataGridView_CellMouseEnter(object sender, DataGridViewCellEventArgs e) { UpdateDataGridCellBackgroundColor(e, Color.LightBlue); } private void QueryResultItemsDataGridView_CellMouseLeave(object sender, DataGridViewCellEventArgs e) { UpdateDataGridCellBackgroundColor(e, Color.White); } private void MapControl_MouseMove(object sender, MouseEventArgs e) { PointShape mouseLocation = ExtentHelper.ToWorldCoordinate(map.CurrentExtent, new ScreenPointF(e.X, e.Y), map.Width, map.Height); lblFooterLocationX.Text = string.Format(CultureInfo.InvariantCulture, "X:{0:N2}", mouseLocation.X); lblFooterLocationY.Text = string.Format(CultureInfo.InvariantCulture, "Y:{0:N2}", mouseLocation.Y); } private void OverlaySwitcherPictureBox_Click(object sender, EventArgs e) { PictureBox tempPictureBox = (PictureBox)sender; tempPictureBox.Cursor = Cursors.Hand; if (switcher != null) { switcher.Visible = !switcher.Visible; tempPictureBox.Image = switcher.Visible ? Resources.switcher_minimize : Resources.switcher_maxmize; } } private void RefreshMarkersByFeatures(IEnumerable<Feature> features) { markerMemoryLayer.InternalFeatures.Clear(); markerMemoryHighlightLayer.InternalFeatures.Clear(); if (features != null) { foreach (Feature item in features) { markerMemoryLayer.InternalFeatures.Add(item); } } map.Refresh(map.Overlays["QueryResultMarkerOverlay"]); } private void UpdateDataGridCellBackgroundColor(DataGridViewCellEventArgs e, Color newColor) { if (e.ColumnIndex == 0 && e.RowIndex >= 0) { DataGridViewCell cell = QueryResultItemsDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex]; if (cell.Value != null) { cell.Style.BackColor = newColor; } } } private void InitializeBackground() { pnlQueryTool.BackgroundImage = GetRoundRectangleBitmap(pnlQueryTool); pnlConfigurationTools.BackgroundImage = GetRoundRectangleBitmap(pnlConfigurationTools); } private void InitializeToolTips() { ToolTip panToolTip = new ToolTip(); panToolTip.SetToolTip(PanRadioButton, "Pan the Map"); ToolTip drawCircleToolTip = new ToolTip(); drawCircleToolTip.SetToolTip(rbtnDrawCircle, "Draw Circle Range"); ToolTip drawPolygonToolTip = new ToolTip(); drawPolygonToolTip.SetToolTip(rbtnDrawPolygon, "Draw Polygon Range"); ToolTip drawRectangleToolTip = new ToolTip(); drawRectangleToolTip.SetToolTip(rbtnDrawRectangle, "Draw Rectangle Range"); ToolTip clearSelectionToolTip = new ToolTip(); clearSelectionToolTip.SetToolTip(rbtnClearAll, "Clear Selection"); ToolTip heatMapToolTip = new ToolTip(); heatMapToolTip.SetToolTip(HeatMapRadioButton, "Heat Map"); ToolTip pointMapToolTip = new ToolTip(); pointMapToolTip.SetToolTip(rbtnPointMap, "Regular Point Map"); ToolTip isoLineMapToolTip = new ToolTip(); isoLineMapToolTip.SetToolTip(rbtnIsoMap, "IsoLines Map"); } private void QueryResultItemsDataGridView_SizeChanged(object sender, EventArgs e) { cluEmpty.Width = QueryResultItemsDataGridView.Width - cluDepth.Width - cluLatitude.Width - cluLongitude.Width - cluMagnitude.Width - cluYear.Width - cluZoomto.Width - 10; } private void LeftSideBarPanel_PanelCollapseButtonClick(object sender, EventArgs e) { dataAndMapSpliter.Width = Width - leftSideBarPanel.Width - 15; dataAndMapSpliter.Left = leftSideBarPanel.Width; } private static Bitmap GetRoundRectangleBitmap(Control panel) { Bitmap panelBitmap = new Bitmap(panel.Width - 1, panel.Height - 1); using (Graphics g = Graphics.FromImage(panelBitmap)) { g.SmoothingMode = SmoothingMode.HighQuality; Rectangle drawingRectangle = new Rectangle(0, 0, panelBitmap.Width, panelBitmap.Height); GraphicsPath path = MapSuiteSampleHelper.CreateRoundPath(drawingRectangle, 10); g.DrawPath(new Pen(Color.LightGray, 1), path); } return panelBitmap; } } }
using System; using System.Diagnostics; using System.Windows.Forms; namespace ThinkGeo.MapSuite.EarthquakeStatistics { public partial class BingMapsApplicationIdPromptForm : Form { public BingMapsApplicationIdPromptForm() { InitializeComponent(); } public string ApplicationId { get { return applicationIdTextBox.Text; } } private void OkButton_Click(object sender, EventArgs e) { DialogResult = DialogResult.OK; } private void BingPortalLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { Process.Start("https://www.bingmapsportal.com/"); } } }
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Linq; using System.Windows.Forms; using ThinkGeo.MapSuite.EarthquakeStatistics.Properties; namespace ThinkGeo.MapSuite.EarthquakeStatistics { public class CollapsiblePanel : Panel { private int lineWidth; private int panelWidth; private bool isCollapsible; private Size collapsibleBoxSize; private PictureBox pictureCollapsibleBox; public event EventHandler PanelCollapseButtonClick; public CollapsiblePanel() { lineWidth = 5; isCollapsible = false; collapsibleBoxSize = new Size(12, 110); pictureCollapsibleBox = new PictureBox(); pictureCollapsibleBox.Cursor = Cursors.Hand; pictureCollapsibleBox.BackColor = Color.Transparent; pictureCollapsibleBox.Location = new Point(Width - lineWidth - collapsibleBoxSize.Width, Height / 2 - collapsibleBoxSize.Height / 2); pictureCollapsibleBox.Size = collapsibleBoxSize; pictureCollapsibleBox.Image = GetCollapsibleImage(); pictureCollapsibleBox.Click += PictureCollapsibleBox_Click; pictureCollapsibleBox.MouseEnter += PictureCollapsibleBox_MouseEnter; pictureCollapsibleBox.MouseLeave += PictureCollapsibleBox_MouseLeave; Controls.Add(pictureCollapsibleBox); Width = lineWidth + panelWidth + pictureCollapsibleBox.Width; Resize += CollapsiblePanel_Resize; } public int LineWidth { get { return lineWidth; } set { lineWidth = value; } } public int PanelWidth { get { return panelWidth; } set { panelWidth = value; } } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); if (Height > 0) { Rectangle drawingRectangle = new Rectangle(Width - lineWidth, 0, lineWidth, Height); LinearGradientBrush myBrush = new LinearGradientBrush(drawingRectangle, Color.Gray, Color.White, LinearGradientMode.Horizontal); e.Graphics.FillRectangle(myBrush, drawingRectangle); } } protected void OnPanelCollapseButtonClick(EventArgs e) { EventHandler handler = PanelCollapseButtonClick; if (handler != null) handler(this, e); } private void CollapsiblePanel_Resize(object sender, EventArgs e) { pictureCollapsibleBox.Location = new Point(Width - lineWidth - collapsibleBoxSize.Width, Height / 2 - collapsibleBoxSize.Height / 2); } private Bitmap GetCollapsibleImage() { if (pictureCollapsibleBox.Image != null) { pictureCollapsibleBox.Image.Dispose(); } Bitmap bitmap = new Bitmap(pictureCollapsibleBox.Size.Width, pictureCollapsibleBox.Size.Height); using (Graphics g = Graphics.FromImage(bitmap)) { Size imageSize = Resources.collapse.Size; int x = (pictureCollapsibleBox.Width - imageSize.Width) / 2; int y = (pictureCollapsibleBox.Height - imageSize.Height) / 2; g.DrawImage(isCollapsible ? Resources.expand : Resources.collapse, x, y); } return bitmap; } private void PictureCollapsibleBox_Click(object sender, EventArgs e) { isCollapsible = !isCollapsible; pictureCollapsibleBox.Image = GetCollapsibleImage(); foreach (Control item in Controls.OfType<Control>().Where(c => c != pictureCollapsibleBox)) { item.Visible = !isCollapsible; } Width = isCollapsible ? lineWidth + collapsibleBoxSize.Width : panelWidth + lineWidth + collapsibleBoxSize.Width; OnPanelCollapseButtonClick(e); Refresh(); } private void PictureCollapsibleBox_MouseEnter(object sender, EventArgs e) { pictureCollapsibleBox.BackColor = Color.FromArgb(150, 4, 60, 153); } private void PictureCollapsibleBox_MouseLeave(object sender, EventArgs e) { pictureCollapsibleBox.BackColor = Color.Transparent; } } }
using System; using ThinkGeo.MapSuite.DesktopEdition; namespace ThinkGeo.MapSuite.EarthquakeStatistics { public class OverlayChangedOverlaySwitcherEventArgs : EventArgs { public OverlayChangedOverlaySwitcherEventArgs() : this(null) { } public OverlayChangedOverlaySwitcherEventArgs(Overlay overlay) { Overlay = overlay; } public Overlay Overlay { get; private set; } public bool Cancel { get; set; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Drawing; using System.Linq; using System.Windows.Forms; using ThinkGeo.MapSuite.DesktopEdition; namespace ThinkGeo.MapSuite.EarthquakeStatistics { public partial class OverlaySwitcher : UserControl { public event EventHandler<OverlayChangedOverlaySwitcherEventArgs> OverlayChanged; private WinformsMap mapControl; private Collection<Overlay> overlays; public OverlaySwitcher() : this(null, null) { } public OverlaySwitcher(IEnumerable<Overlay> overlays, WinformsMap map) { this.InitializeComponent(); this.mapControl = map; this.overlays = new Collection<Overlay>(); if (overlays != null) { foreach (var item in overlays) { this.overlays.Add(item); } } LoadUIs(); } public WinformsMap MapControl { get { return mapControl; } set { mapControl = value; } } public Collection<Overlay> Overlays { get { return overlays; } } public void LoadUIs() { if (mapControl == null && overlays.Count == 0) return; int width = 0; int height = 0; int index = 0; foreach (Overlay item in Overlays) { RadioButton radioButton = new RadioButton(); radioButton.UseVisualStyleBackColor = true; radioButton.AutoSize = true; radioButton.TextAlign = ContentAlignment.MiddleLeft; radioButton.Tag = item; radioButton.Text = item.Name; radioButton.Checked = item.IsVisible; radioButton.CheckedChanged += RadioButton_CheckedChanged; height = 5 + index * 20; radioButton.Location = new Point(15, height); if (width < radioButton.Width) { width = radioButton.Width + 80; } height += radioButton.Height + 10; Controls.Add(radioButton); index++; } Width = width; Height = height; Refresh(); } private void RadioButton_CheckedChanged(object sender, EventArgs e) { RadioButton radioButton = (RadioButton)sender; if (radioButton.Checked) { Overlay currentOverlay = (Overlay)radioButton.Tag; OverlayChangedOverlaySwitcherEventArgs overlaySwitchedEventArgs = new OverlayChangedOverlaySwitcherEventArgs((Overlay)radioButton.Tag); OnOverlaySwitched(overlaySwitchedEventArgs); if (overlaySwitchedEventArgs.Cancel) { radioButton.Checked = false; foreach (RadioButton item in Controls.OfType<RadioButton>()) { Overlay tempOverlay = item.Tag as Overlay; if (tempOverlay != null && tempOverlay.IsVisible) { item.Checked = true; break; } } } else { foreach (Overlay overlay in Overlays) { overlay.IsVisible = currentOverlay == overlay; } mapControl.Refresh(); } } } protected virtual void OnOverlaySwitched(OverlayChangedOverlaySwitcherEventArgs e) { EventHandler<OverlayChangedOverlaySwitcherEventArgs> handler = OverlayChanged; if (handler != null) { handler(this, e); } } } }
using System; using System.ComponentModel; using System.Drawing; using System.Globalization; using System.Windows.Forms; using System.Windows.Forms.Design; using System.Windows.Forms.VisualStyles; namespace ThinkGeo.MapSuite.EarthquakeStatistics { public sealed class SelectionRangeSlider : Control { public event EventHandler LeftValueChanged; public event EventHandler RightValueChanged; public event EventHandler ValueChanged; private int maximum; private int minimum; private int tickNum; private int valueLeft; private int valueRight; private int smallChange; private bool draggingLeft; private bool draggingRight; private Thumbs selectedThumb; private Orientation orientation; private TrackBarThumbState leftThumbState; private TrackBarThumbState rightThumbState; public SelectionRangeSlider() { tickNum = 1; DoubleBuffered = true; SetDefaults(); } [Description("The|maximum value.")] public int Maximum { get { return maximum; } set { if (value <= Minimum) { throw new ArgumentException(string.Format("Value of '{0}' is not valid for 'Maximum'. 'Maximum' should be greater than 'Minimum'.", value.ToString(CultureInfo.InvariantCulture)), "Maximum"); } maximum = value; Invalidate(); } } [Description("The|minimum value.")] public int Minimum { get { return minimum; } set { if (value >= Maximum) { throw new ArgumentException(string.Format("Value of '{0}' is not valid for 'Minimum'. 'Minimum' should be less than 'Maximum'.", value.ToString(CultureInfo.InvariantCulture)), "Minimum"); } minimum = value; Invalidate(); } } [Description("The|orientation of the control.")] public Orientation Orientation { get { return orientation; } set { orientation = value; } } [Description("The|thumb that had focus last.")] public Thumbs SelectedThumb { get { return selectedThumb; } private set { selectedThumb = value; } } [Description("The|amount of positions the closest slider moves when the control is clicked.")] public int SmallChange { get { return smallChange; } set { smallChange = value; } } public int TickNum { get { return tickNum; } set { tickNum = value; } } [Description("The|position of the left slider.")] public int ValueLeft { get { return valueLeft; } set { valueLeft = value; OnValueChanged(EventArgs.Empty); OnLeftValueChanged(EventArgs.Empty); Invalidate(); } } [Description("The|position of the right slider.")] public int ValueRight { get { return valueRight; } set { valueRight = value; OnValueChanged(EventArgs.Empty); OnRightValueChanged(EventArgs.Empty); Invalidate(); } } private double RelativeValueLeft { get { double difference = Maximum - Minimum; return difference == 0 ? ValueLeft : (ValueLeft - Minimum) / difference; } } private double RelativeValueRight { get { double difference = Maximum - Minimum; return difference == 0 ? ValueLeft : (ValueRight - Minimum) / difference; } } public void DecrementLeft() { int newValue = Math.Max(ValueLeft - 1, Minimum); if (IsValidValueLeft(newValue)) ValueLeft = newValue; Invalidate(); } public void DecrementRight() { int newValue = Math.Max(ValueRight - 1, Minimum); if (IsValidValueRight(newValue)) ValueRight = newValue; Invalidate(); } public void IncrementLeft() { int newValue = Math.Min(ValueLeft + 1, Maximum); if (IsValidValueLeft(newValue)) ValueLeft = newValue; Invalidate(); } public void IncrementRight() { int newValue = Math.Min(ValueRight + 1, Maximum); if (IsValidValueRight(newValue)) ValueRight = newValue; Invalidate(); } private void OnLeftValueChanged(EventArgs e) { EventHandler handler = LeftValueChanged; if (handler != null) { handler(this, e); } } protected override void OnMouseDown(MouseEventArgs e) { base.OnMouseDown(e); Focus(); SetThumbState(e.Location, TrackBarThumbState.Pressed); draggingLeft = (leftThumbState == TrackBarThumbState.Pressed); if (!draggingLeft) draggingRight = (rightThumbState == TrackBarThumbState.Pressed); if (draggingLeft) { SelectedThumb = Thumbs.Left; } else if (draggingRight) { SelectedThumb = Thumbs.Right; } if (!draggingLeft && !draggingRight) { if (GetClosestSlider(e.Location) == Thumbs.Left) { if (e.X < GetLeftThumbRectangle().X) DecrementLeft(); else IncrementLeft(); SelectedThumb = Thumbs.Left; } else { if (e.X < GetRightThumbRectangle().X) DecrementRight(); else IncrementRight(); SelectedThumb = Thumbs.Right; } } Invalidate(); } protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); if (draggingLeft || draggingRight) { SetThumbState(e.Location, TrackBarThumbState.Hot); int offset = Convert.ToInt32(e.X / (double)(Width) * (Maximum - Minimum)); int newValue = Minimum + offset; if (draggingLeft && IsValidValueLeft(newValue)) ValueLeft = newValue; else if (draggingRight && IsValidValueRight(newValue)) ValueRight = newValue; Invalidate(); } } protected override void OnMouseUp(MouseEventArgs e) { base.OnMouseUp(e); draggingLeft = false; draggingRight = false; Invalidate(); } protected override void OnMouseWheel(MouseEventArgs e) { base.OnMouseWheel(e); if (e.Delta == 0) return; switch (SelectedThumb) { case Thumbs.Left: if (e.Delta > 0) IncrementLeft(); else DecrementLeft(); break; case Thumbs.Right: if (e.Delta > 0) IncrementRight(); else DecrementRight(); break; } } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); Size thumbSize = GetThumbRectangle(0, e.Graphics).Size; Rectangle trackRect = GetTrackRectangle(Convert.ToInt32(thumbSize.Width / 2)); Rectangle ticksRect = trackRect; ticksRect.Offset(0, 15); Rectangle leftRectangle = GetLeftThumbRectangle(e.Graphics); Rectangle rightRectangle = GetRightThumbRectangle(e.Graphics); Rectangle highlightRectangle = new Rectangle((leftRectangle.X + leftRectangle.Width / 2), trackRect.Y, (rightRectangle.X + rightRectangle.Width / 2) - (leftRectangle.X + leftRectangle.Width / 2), trackRect.Height); TrackBarRenderer.DrawVerticalTrack(e.Graphics, trackRect); TrackBarRenderer.DrawHorizontalTicks(e.Graphics, ticksRect, (Maximum - Minimum) / TickNum + 1, EdgeStyle.Etched); e.Graphics.FillRectangle(new SolidBrush(Color.FromArgb(64, 141, 219)), highlightRectangle); TrackBarRenderer.DrawBottomPointingThumb(e.Graphics, GetLeftThumbRectangle(e.Graphics), leftThumbState); TrackBarRenderer.DrawBottomPointingThumb(e.Graphics, GetRightThumbRectangle(e.Graphics), rightThumbState); } private void OnRightValueChanged(EventArgs e) { EventHandler handler = RightValueChanged; if (handler != null) { handler(this, e); } } private void OnValueChanged(EventArgs e) { EventHandler handler = ValueChanged; if (handler != null) { handler(this, e); } } private Thumbs GetClosestSlider(Point point) { Rectangle leftThumbRect = GetLeftThumbRectangle(); Rectangle rightThumbRect = GetRightThumbRectangle(); if (Orientation == Orientation.Horizontal) { if (Math.Abs(leftThumbRect.X - point.X) > Math.Abs(rightThumbRect.X - point.X) && Math.Abs(leftThumbRect.Right - point.X) > Math.Abs(rightThumbRect.Right - point.X)) { return Thumbs.Right; } return Thumbs.Left; } if (Math.Abs(leftThumbRect.Y - point.Y) > Math.Abs(rightThumbRect.Y - point.Y) && Math.Abs(leftThumbRect.Bottom - point.Y) > Math.Abs(rightThumbRect.Bottom - point.Y)) { return Thumbs.Right; } return Thumbs.Left; } private Rectangle GetLeftThumbRectangle(Graphics g = null) { bool shouldDispose = (g == null); if (shouldDispose) g = CreateGraphics(); Rectangle rect = GetThumbRectangle(RelativeValueLeft, g); if (shouldDispose) g.Dispose(); return rect; } private Rectangle GetRightThumbRectangle(Graphics g = null) { bool shouldDispose = (g == null); if (shouldDispose) g = CreateGraphics(); Rectangle rect = GetThumbRectangle(RelativeValueRight, g); if (shouldDispose) g.Dispose(); return rect; } private Rectangle GetThumbRectangle(double relativeValue, Graphics g) { Size size = TrackBarRenderer.GetBottomPointingThumbSize(g, TrackBarThumbState.Normal); int border = Convert.ToInt32(size.Width / 2); int w = GetTrackRectangle(border).Width; int x = Convert.ToInt32(0 / (Maximum - Minimum) * w + relativeValue * w); int y = Convert.ToInt32((Height - size.Height) / 2); return new Rectangle(new Point(x, y), size); } private Rectangle GetTrackRectangle(int border) { return new Rectangle(border, Convert.ToInt32(Height / 2) - 3, Width - 2 * border - 1, 4); } private bool IsValidValueLeft(int value) { return (value >= Minimum && value <= Maximum && value < ValueRight); } private bool IsValidValueRight(int value) { return (value >= Minimum && value <= Maximum && value > ValueLeft); } private void SetDefaults() { Orientation = Orientation.Horizontal; SmallChange = 1; Maximum = 10; Minimum = 0; ValueLeft = 0; ValueRight = 7; } private void SetThumbState(Point location, TrackBarThumbState newState) { Rectangle leftThumbRect = GetLeftThumbRectangle(); Rectangle rightThumbRect = GetRightThumbRectangle(); if (leftThumbRect.Contains(location)) { leftThumbState = newState; } else { leftThumbState = SelectedThumb == Thumbs.Left ? TrackBarThumbState.Hot : TrackBarThumbState.Normal; } if (rightThumbRect.Contains(location)) { rightThumbState = newState; } else { rightThumbState = SelectedThumb == Thumbs.Right ? TrackBarThumbState.Hot : TrackBarThumbState.Normal; } } internal class DoubleTrackBarDesigner : ControlDesigner { private SelectionRangeSlider TrackBar { get { return (SelectionRangeSlider)Control; } } protected override bool GetHitTest(Point point) { Point pt = TrackBar.PointToClient(point); if (TrackBar.GetLeftThumbRectangle().Contains(pt) || TrackBar.GetRightThumbRectangle().Contains(pt)) { return true; } return base.GetHitTest(point); } } } public enum Thumbs { None = 0, Left = 1, Right = 2 } }
using System; using System.Configuration; using System.Drawing; using System.Drawing.Drawing2D; using System.Globalization; using System.IO; using System.Net; using System.Windows.Forms; using System.Xml; using ThinkGeo.MapSuite.Core; namespace ThinkGeo.MapSuite.EarthquakeStatistics { public static class MapSuiteSampleHelper { public static string GetBingMapsKey() { string exePath = Application.ExecutablePath; Configuration config = ConfigurationManager.OpenExeConfiguration(exePath); KeyValueConfigurationElement appMapKeySetting = config.AppSettings.Settings["BingMapKey"]; string bingMapsKey = appMapKeySetting != null ? appMapKeySetting.Value : string.Empty; if (string.IsNullOrEmpty(bingMapsKey)) { BingMapsApplicationIdPromptForm inputBingMapKeyWindow = new BingMapsApplicationIdPromptForm(); inputBingMapKeyWindow.Owner = Application.OpenForms[0]; if (inputBingMapKeyWindow.ShowDialog() == DialogResult.OK && IsBingMapsKeyValid(inputBingMapKeyWindow.ApplicationId)) { bingMapsKey = inputBingMapKeyWindow.ApplicationId; config.AppSettings.Settings.Add("BingMapKey", bingMapsKey); config.Save(); ConfigurationManager.RefreshSection("appSettings"); } } return bingMapsKey; } public static GraphicsPath CreateRoundPath(Rectangle rect, int arcRadius) { GraphicsPath path = new GraphicsPath(); if (rect.Width == 0 || rect.Height == 0) { return path; } if (arcRadius > 0) { path.AddArc(rect.Left, rect.Top, arcRadius, arcRadius, 180, 90); path.AddArc(rect.Right - arcRadius, rect.Top, arcRadius, arcRadius, -90, 90); path.AddArc(rect.Right - arcRadius, rect.Bottom - arcRadius, arcRadius, arcRadius, 0, 90); path.AddArc(rect.Left, rect.Bottom - arcRadius, arcRadius, arcRadius, 90, 90); } path.CloseFigure(); return path; } private static bool IsBingMapsKeyValid(string BingMapsKey) { bool isValid = false; const string loginServiceTemplate = "http://dev.virtualearth.net/REST/v1/Imagery/Metadata/{0}?&incl=ImageryProviders&o=xml&key={1}"; try { string loginServiceUri = String.Format(CultureInfo.InvariantCulture , loginServiceTemplate, BingMapsMapType.Road, BingMapsKey); WebRequest request = WebRequest.Create(loginServiceUri); WebResponse response = request.GetResponse(); Stream stream = response.GetResponseStream(); XmlDocument xDoc = new XmlDocument(); xDoc.Load(stream); XmlNamespaceManager nsmgr = new XmlNamespaceManager(xDoc.NameTable); nsmgr.AddNamespace("bing", "http://schemas.microsoft.com/search/local/ws/rest/v1"); XmlNode root = xDoc.SelectSingleNode("bing:Response", nsmgr); XmlNode imageUrlElement = root.SelectSingleNode("bing:ResourceSets/bing:ResourceSet/bing:Resources/bing:ImageryMetadata/bing:ImageUrl", nsmgr); XmlNodeList subdomainsElement = root.SelectNodes("bing:ResourceSets/bing:ResourceSet/bing:Resources/bing:ImageryMetadata/bing:ImageUrlSubdomains/bing:string", nsmgr); if (imageUrlElement != null && subdomainsElement != null) { isValid = true; } } catch (Exception ex) { MessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); } return isValid; } } }
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() { heatLayer = new HeatLayer(); FeatureSource = featureSource; } public new FeatureSource FeatureSource { get { return base.FeatureSource; } set { base.FeatureSource = value; heatLayer.FeatureSource = 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.Globalization; using System.Linq; using ThinkGeo.MapSuite.Core; using ThinkGeo.MapSuite.EarthquakeStatistics.Properties; namespace ThinkGeo.MapSuite.EarthquakeStatistics { public class EarthquakeIsoLineFeatureLayer : FeatureLayer { private DynamicIsoLineLayer isoLineLayer; private ClassBreakStyle levelClassBreakStyle; public EarthquakeIsoLineFeatureLayer() : this(null) { } public EarthquakeIsoLineFeatureLayer(FeatureSource featureSource) { if (featureSource != null) 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(); IEnumerable<double> isoLineLevels = GetClassBreakValues(dataPoints.Select(n => n.Value), 12); GridInterpolationModel gridInterpolationModel = new InverseDistanceWeightedGridInterpolationModel(3, double.MaxValue); isoLineLayer = new DynamicIsoLineLayer(dataPoints, isoLineLevels, gridInterpolationModel, 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); //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(GetReturningColumnNames()) 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 IEnumerable<double> GetClassBreakValues(IEnumerable<double> values, int count) { double[] orderedValues = values.OrderBy(v => v).ToArray(); int increament = orderedValues.Length / count; Collection<double> result = new Collection<double>(); for (int i = 1; i < count; i++) { result.Add(orderedValues[i|* increament]); } return result; } private static IEnumerable<string> GetReturningColumnNames() { yield return Resources.LongitudeColumnName; yield return Resources.LatitudeColumnName; yield return Resources.MagnitudeColumnName; } } }
using System.Drawing; using System.Windows.Forms; using ThinkGeo.MapSuite.Core; using ThinkGeo.MapSuite.EarthquakeStatistics.Properties; namespace ThinkGeo.MapSuite.EarthquakeStatistics { public class EarthquakeItem { private static readonly Icon findIcon = Icon.FromHandle(Resources.find.GetHicon()); private Feature epicenterFeature; private DataGridViewTextBoxCell yearCell; private DataGridViewTextBoxCell depth_KMCell; private DataGridViewImageCell imageButtonCell; private DataGridViewTextBoxCell latitudeCell; private DataGridViewTextBoxCell locationCell; private DataGridViewTextBoxCell longitudeCell; private DataGridViewTextBoxCell magnitudeCell; private DataGridViewTextBoxCell locationPointCell; public EarthquakeItem() : this(null) { } public EarthquakeItem(Feature epicenterFeature) { imageButtonCell = new DataGridViewImageCell(); imageButtonCell.Style.SelectionBackColor = Color.Transparent; imageButtonCell.Value = findIcon; depth_KMCell = new DataGridViewTextBoxCell(); yearCell = new DataGridViewTextBoxCell(); locationCell = new DataGridViewTextBoxCell(); longitudeCell = new DataGridViewTextBoxCell(); latitudeCell = new DataGridViewTextBoxCell(); magnitudeCell = new DataGridViewTextBoxCell(); locationPointCell = new DataGridViewTextBoxCell(); EpicenterFeature = epicenterFeature; } public DataGridViewTextBoxCell DepthInKilometerCell { get { return depth_KMCell; } set { depth_KMCell = value; } } public DataGridViewImageCell ImageButtonCell { get { return imageButtonCell; } set { imageButtonCell = value; } } public DataGridViewTextBoxCell LatitudeCell { get { return latitudeCell; } set { latitudeCell = value; } } public DataGridViewTextBoxCell LocationCell { get { return locationCell; } set { locationCell = value; } } public DataGridViewTextBoxCell LongitudeCell { get { return longitudeCell; } set { longitudeCell = value; } } public DataGridViewTextBoxCell MagnitudeCell { get { return magnitudeCell; } set { magnitudeCell = value; } } public Feature EpicenterFeature { get { return epicenterFeature; } set { epicenterFeature = value; if (epicenterFeature != null) { depth_KMCell.Value = GetTextFromDoubleTypeColumnValue(epicenterFeature, Resources.DepthColumnName); yearCell.Value = GetTextFromDoubleTypeColumnValue(epicenterFeature, Resources.YearColumnName); locationCell.Value = GetTextFromColumnValue(epicenterFeature, Resources.LocationColumnName); longitudeCell.Value = GetTextFromColumnValue(epicenterFeature, Resources.LongitudeColumnName); latitudeCell.Value = GetTextFromColumnValue(epicenterFeature, Resources.LatitudeColumnName); magnitudeCell.Value = GetTextFromDoubleTypeColumnValue(epicenterFeature, Resources.MagnitudeColumnName); locationPointCell.Value = epicenterFeature.GetWellKnownText(); } } } public DataGridViewTextBoxCell YearCell { get { return yearCell; } set { yearCell = value; } } public DataGridViewTextBoxCell LocationPointCell { get { return locationPointCell; } set { locationPointCell = value; } } private static string GetTextFromColumnValue(Feature feature, string columnName) { string text = string.Empty; if (feature.ColumnValues.ContainsKey(columnName)) { text = feature.ColumnValues[columnName]; } return text; } private static string GetTextFromDoubleTypeColumnValue(Feature feature, string columnName) { string text = Resources.UnknownString; if (feature.ColumnValues.ContainsKey(columnName)) { double value; if (double.TryParse(feature.ColumnValues[columnName], out value)) { text = value >= 0 ? feature.ColumnValues[columnName] : Resources.UnknownString; } } return text; } } }
using System.Globalization; using ThinkGeo.MapSuite.Core; using ThinkGeo.MapSuite.DesktopEdition; namespace ThinkGeo.MapSuite.EarthquakeStatistics { public class RadiusMearsureTrackInteractiveOverlay : TrackInteractiveOverlay { private bool isTracking; private LineShape radiusLine; private GeographyUnit mapUnit; private string radiusValueString; private Vertex circleCenterVertex; private DistanceUnit distanceUnit; private ScreenPointF mouseScreenPointF; public RadiusMearsureTrackInteractiveOverlay() : this(DistanceUnit.Mile, GeographyUnit.DecimalDegree) { } public RadiusMearsureTrackInteractiveOverlay(DistanceUnit distanceUnit, GeographyUnit mapUnit) { this.mapUnit = mapUnit; this.distanceUnit = distanceUnit; TrackShapeLayer.ZoomLevelSet.ZoomLevel01.DefaultPointStyle = PointStyles.CreateSimpleCircleStyle(GeoColor.SimpleColors.DarkBlue, 8); TrackShapeLayer.ZoomLevelSet.ZoomLevel01.DefaultLineStyle = LineStyles.CreateSimpleLineStyle(GeoColor.SimpleColors.White, 3, true); TrackShapeLayer.ZoomLevelSet.ZoomLevel01.DefaultAreaStyle = AreaStyles.CreateSimpleAreaStyle(GeoColor.FromArgb(80, GeoColor.SimpleColors.LightGreen), GeoColor.SimpleColors.White, 2); TrackShapeLayer.ZoomLevelSet.ZoomLevel01.ApplyUntilZoomLevel = ApplyUntilZoomLevel.Level20; } protected override InteractiveResult MouseDownCore(InteractionArguments interactionArguments) { if (TrackMode == TrackMode.Circle) { circleCenterVertex = new Vertex(interactionArguments.WorldX, interactionArguments.WorldY); TrackShapeLayer.InternalFeatures.Add("center", new Feature(circleCenterVertex)); } return base.MouseDownCore(interactionArguments); } protected override InteractiveResult MouseMoveCore(InteractionArguments interactionArguments) { InteractiveResult arguments = base.MouseMoveCore(interactionArguments); if (Vertices.Count == 0) { radiusValueString = string.Empty; } else if (TrackMode == TrackMode.Circle) { Vertex currentVertex = new Vertex(interactionArguments.WorldX, interactionArguments.WorldY); radiusLine = new LineShape(new[] { circleCenterVertex, currentVertex }); TrackShapeLayer.InternalFeatures["radius"] = new Feature(radiusLine); mouseScreenPointF = new ScreenPointF(interactionArguments.ScreenX + 10, interactionArguments.ScreenY - 10); } return arguments; } protected override void OnDrawing(DrawingOverlayEventArgs e) { DrawMeasureResult(e.GeoCanvas); base.OnDrawing(e); } protected override void OnMapMouseUp(MapMouseUpInteractiveOverlayEventArgs e) { base.OnMapMouseUp(e); if (TrackMode == TrackMode.Circle) { if (TrackShapeLayer.InternalFeatures.Contains("center")) { TrackShapeLayer.InternalFeatures.Remove("center"); } if (TrackShapeLayer.InternalFeatures.Contains("radius")) { TrackShapeLayer.InternalFeatures.Remove("radius"); } } } protected override void OnTrackEnded(TrackEndedTrackInteractiveOverlayEventArgs e) { isTracking = false; base.OnTrackEnded(e); } protected override void OnTrackStarting(TrackStartingTrackInteractiveOverlayEventArgs e) { isTracking = true; base.OnTrackStarting(e); } private void DrawMeasureResult(GeoCanvas canvas) { if (TrackMode == TrackMode.Circle && isTracking) { if (TrackShapeLayer.InternalFeatures.Count > 0 && radiusLine != null) { double r = radiusLine.GetLength(mapUnit, distanceUnit); radiusValueString = string.Format(CultureInfo.InvariantCulture, "{0:N3} {1}", r, GetAbbreviateDistanceUnit(distanceUnit)); canvas.DrawTextWithScreenCoordinate(radiusValueString, new GeoFont(), new GeoSolidBrush(GeoColor.SimpleColors.Black), mouseScreenPointF.X, mouseScreenPointF.Y, DrawingLevel.LabelLevel); } } } private static string GetAbbreviateDistanceUnit(DistanceUnit unit) { switch (unit) { case DistanceUnit.Mile: return "mi"; case DistanceUnit.Kilometer: return "km"; case DistanceUnit.Meter: return "m"; case DistanceUnit.Inch: return "in"; default: return "."; } } } }