GisDevelop_Exp/GisDevelop_Exp/MainWindow.xaml.cs
2024-12-05 23:57:27 +08:00

1650 lines
72 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Esri.ArcGISRuntime.Data;
using Esri.ArcGISRuntime.Mapping;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Portal;
using Esri.ArcGISRuntime.Rasters;
using Esri.ArcGISRuntime.Security;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.UI;
using Esri.ArcGISRuntime.UI.Controls;
using Color = System.Drawing.Color;
using Geometry = Esri.ArcGISRuntime.Geometry.Geometry;
using Polygon = Esri.ArcGISRuntime.Geometry.Polygon;
using Polyline = Esri.ArcGISRuntime.Geometry.Polyline;
enum CURRENTOPERATION
{
NullOpe = -1,
SelectQuery = 0,
IdentifyQuery,
PanMap,
DrawPoint,
DrawLine,
DrawPolygon,
Cal_Clip,
Cal_Cut,
Cal_Union,
Cal_IntersectPoint,
Cal_Simplify,
Cal_Intersect,
Cal_Intersection,
Cal_Gene,
Cal_Buff,
AttributeQuery,
ClickQuery,
ExtentQuery
}
namespace GisDevelop_Exp
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private FeatureLayer _featureLayer;
private string _statesUrl =
"https://services.arcgis.com/jIL9msH9OI208GCb/arcgis/rest/services/USA_Daytime_Population_2016/FeatureServer/0";
private ServiceFeatureTable _featureTable;
private List<MapPoint> linePoints;
private List<Graphic> linesList;
private SimpleMarkerSymbol pointSymbol;
private SimpleLineSymbol lineSymbol;
private SimpleFillSymbol fillSymbol;
private SimpleLineSymbol outlineSymbol;
private Symbol pSymbol;
private ListBoxItem cur_LayerItem;
private GraphicsOverlay _pGraphicsOverLay;
private Point _startPoint;
private List<Graphic> listOfClipGraphics; //几何操作时选择的图形
private int selByGeometryType = 0;
LocationQueryResultsWindow locationQueryResultsWindow;
private MapPoint _startLocation;
private readonly Dictionary<string, Basemap> _basemapOptions = new Dictionary<string, Basemap>()
{
{ "Streets (Raster)", new Basemap(BasemapStyle.OSMStreets) },
{ "Streets (Vector)", new Basemap(BasemapStyle.OSMStreetsRelief) },
{ "Streets - Night (Vector)", new Basemap(BasemapStyle.ArcGISStreetsNight) },
{ "Imagery (Raster)", new Basemap(BasemapStyle.ArcGISImagery) },
{ "Imagery with Labels (Raster)", new Basemap(BasemapStyle.ArcGISImageryLabels) },
{ "Imagery with Labels (Vector)", new Basemap(BasemapStyle.ArcGISImageryStandard) },
{ "Dark Gray Canvas (Vector)", new Basemap(BasemapStyle.ArcGISDarkGray) },
{ "Light Gray Canvas (Raster)", new Basemap(BasemapStyle.ArcGISLightGray) },
{ "Light Gray Canvas (Vector)", new Basemap(BasemapStyle.ArcGISLightGrayBase) },
{ "Navigation (Vector)", new Basemap(BasemapStyle.ArcGISNavigation) },
{ "OpenStreetMap (Raster)", new Basemap(BasemapStyle.OSMNavigation) }
};
private CURRENTOPERATION m_CurOper;
List<System.Drawing.Color> ColorArray = new List<Color>
{
Color.AliceBlue, Color.AntiqueWhite, Color.Aqua, Color.Aquamarine, Color.Azure,
Color.Beige, Color.Bisque, Color.Black, Color.BlanchedAlmond, Color.Blue, Color.Brown,
Color.BurlyWood, Color.CadetBlue, Color.Chocolate, Color.Coral, Color.CornflowerBlue,
Color.Cornsilk, Color.Crimson, Color.Cyan, Color.FloralWhite, Color.Green, Color.GreenYellow,
Color.HotPink, Color.LawnGreen, Color.Magenta
};
public MainWindow()
{
InitializeComponent();
pointSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Circle, System.Drawing.Color.Blue, 3);
lineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.Blue, 1);
fillSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle.Solid, System.Drawing.Color.Blue,
new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.Pink, 1));
outlineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.Blue, 1);
linePoints = new List<MapPoint>();
linesList = new List<Graphic>();
m_CurOper = CURRENTOPERATION.NullOpe;
Initialize();
EagleMapView.Map = new Map(BasemapStyle.ArcGISImageryStandard);
GraphicsOverlay graphicLayer = new GraphicsOverlay();
MainMapView.GraphicsOverlays.Add(graphicLayer);
listOfClipGraphics = new List<Graphic>();
}
private void Initialize()
{
MainMapView.Map = new Map(_basemapOptions.Values.First());
BasemapChooser.ItemsSource = _basemapOptions.Keys;
BasemapChooser.SelectedIndex = 0;
string token =
"AAPTxy8BH1VEsoebNVZXo8HurGPYSDOnAeIwA4pOmn4FxRfMsbp3zN7aIhAzuRolPS6JUAtf98pdWdQp1jjclJhIB-7QXbTXrBITqXti07DnOLsRnS9lGLYGImGh5vW_jSlnEBqxbbZQCs4S0y5-tHC0_kSFW9RD3Kv8hiDGt1IGSrs-96vwz6rycPenwu_cAwZHZyTahSAEHOR5A7j2y9sUsZ8HoYLcn2O9SI8OYw2tzr4xAAwqN1fcw6FMiVVpBSYWAT1_A4CN5Ivr";
InitializeAuthenticationManagerWithToken(token);
}
private void InitializeAuthenticationManagerWithToken(string token)
{
AuthenticationManager.Current.AddCredential(new OAuthTokenCredential(
new Uri("https://services3.arcgis.com/Po7vxnPH4Do7ht5I/arcgis/rest/services/test/MapServer"), token));
}
private void Menu_OpenShp_Click(object sender, RoutedEventArgs e)
{
OpenShp();
}
private async void OpenShp()
{
System.Windows.Forms.OpenFileDialog fileDialog = new System.Windows.Forms.OpenFileDialog();
fileDialog.Multiselect = true;
fileDialog.Filter = "Shapefile文件(*.shp)|*.shp";
fileDialog.Title = "打开Shapefile文件";
if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
for (int i = 0; i < fileDialog.FileNames.Length; i++)
{
String filePath = fileDialog.FileNames.GetValue(i).ToString();
ShapefileFeatureTable openedFeature = await ShapefileFeatureTable.OpenAsync(filePath);
FeatureLayer opendFeatureLayer = new FeatureLayer(openedFeature);
MainMapView.Map.OperationalLayers.Add(opendFeatureLayer);
await MainMapView.SetViewpointGeometryAsync(openedFeature.Extent);
}
}
AddLayerNameToList();
}
private async void OpenGeoDatabase()
{
string _slocalGeodatabasePath = "";
Geodatabase _localGeodatabase;
System.Windows.Forms.OpenFileDialog fileDialog = new System.Windows.Forms.OpenFileDialog();
fileDialog.Filter = "Geodatabase文件(*.geodatabase)|*.geodatabase";
if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
_slocalGeodatabasePath = fileDialog.FileName;
}
if (System.IO.File.Exists(_slocalGeodatabasePath))
{
_localGeodatabase = await Geodatabase.OpenAsync(_slocalGeodatabasePath);
Map geodatabaseMap = new Map();
int beginCount = _localGeodatabase.GeodatabaseFeatureTables.Count - 1;
for (int i = beginCount; i >= 0; i--)
{
GeodatabaseFeatureTable table = _localGeodatabase.GeodatabaseFeatureTables[i];
await table.LoadAsync();
FeatureLayer layer = new FeatureLayer(table);
layer.Name = table.TableName;
// geodatabaseMap.OperationalLayers.Add(layer);
_featureLayer = layer;
MainMapView.Map.OperationalLayers.Add(layer);
}
Viewpoint geodatabaseViewPoint = new Viewpoint(_featureLayer.FullExtent);
// geodatabaseMap.InitialViewpoint = geodatabaseViewPoint;
MainMapView.Map.InitialViewpoint = geodatabaseViewPoint;
// MainMapView.Map = geodatabaseMap;
}
AddLayerNameToList();
}
private void Menu_OpenGeodatabase_Click(object sender, RoutedEventArgs e)
{
OpenGeoDatabase();
}
private void MainMapView_OnViewpointChanged(object? sender, EventArgs e)
{
EagleMapView.GraphicsOverlays.Clear();
Esri.ArcGISRuntime.Geometry.Polygon vExtent = MainMapView.VisibleArea;
Envelope eagleViewEnvelop = vExtent.Extent;
Color lineColor = Color.FromArgb(255, 255, 0, 0);
SimpleLineSymbol lineSymbol =
new Esri.ArcGISRuntime.Symbology.SimpleLineSymbol(SimpleLineSymbolStyle.Dash, lineColor, 2.0);
Color fillColor = Color.FromArgb(0, 0, 0, 0);
SimpleFillSymbol fillSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle.Solid, fillColor, lineSymbol);
var graphicOverlay = new Esri.ArcGISRuntime.UI.GraphicsOverlay();
var envGraphic = new Esri.ArcGISRuntime.UI.Graphic(eagleViewEnvelop, fillSymbol);
graphicOverlay.Graphics.Add(envGraphic);
EagleMapView.GraphicsOverlays.Add(graphicOverlay);
}
private double GetDistance(MapPoint p1, MapPoint p2)
{
double dx = p2.X - p1.X;
double dy = p2.Y - p1.Y;
return Math.Sqrt(dx * dx + dy * dy);
}
private double GetAngle(MapPoint p1, MapPoint p2)
{
double dx = p2.X - p1.X;
double dy = p2.Y - p1.Y;
return Math.Atan2(dy, dx) * 180 / Math.PI;
}
private void Menu_Zoom_in_OnClick(object sender, RoutedEventArgs e)
{
try
{
Viewpoint initViewpoint = MainMapView.GetCurrentViewpoint(ViewpointType.CenterAndScale);
MainMapView.SetViewpointScaleAsync(initViewpoint.TargetScale / 2.0);
}
catch (Exception exception)
{
Console.WriteLine(exception);
throw;
}
}
private void Menu_Zoom_out_OnClick(object sender, RoutedEventArgs e)
{
try
{
Viewpoint initViewpoint = MainMapView.GetCurrentViewpoint(ViewpointType.CenterAndScale);
MainMapView.SetViewpointScaleAsync(initViewpoint.TargetScale * 2.0);
Console.WriteLine(initViewpoint.TargetScale);
}
catch (Exception exception)
{
Console.WriteLine(exception);
throw;
}
}
private void Menu_OpenOnlineMap_OnClick(object sender, RoutedEventArgs e)
{
OpenOnlineData();
}
private async void OpenOnlineData()
{
Map pMap = new Map();
pMap.Basemap = new Basemap(BasemapStyle.ArcGISTopographicBase);
_featureTable = new ServiceFeatureTable(new Uri(_statesUrl));
_featureLayer = new FeatureLayer(_featureTable);
_featureLayer.MaxScale = 1.0;
await _featureLayer.LoadAsync();
Viewpoint pVP = new Viewpoint(_featureLayer.FullExtent);
pMap.InitialViewpoint = pVP;
SimpleMarkerSymbol pMarkerSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Circle, Color.Blue, 5.0);
SimpleLineSymbol pLineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.Red, 5.0);
SimpleFillSymbol pFillSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle.Solid, Color.Pink, pLineSymbol);
SimpleRenderer pRenderer = new SimpleRenderer();
if (_featureLayer.FeatureTable.GeometryType == GeometryType.Polygon)
{
pRenderer.Symbol = pFillSymbol;
}
else if (_featureLayer.FeatureTable.GeometryType == GeometryType.Point)
{
pRenderer.Symbol = pMarkerSymbol;
}
else if (_featureLayer.FeatureTable.GeometryType == GeometryType.Polyline)
{
pRenderer.Symbol = pLineSymbol;
}
else
{
pRenderer.Symbol = pFillSymbol;
}
_featureLayer.Renderer = pRenderer;
pMap.OperationalLayers.Add(_featureLayer);
MainMapView.Map = pMap;
MainMapView.SelectionProperties.Color = Color.Cyan;
AddLayerNameToList();
}
private void BasemapChooser_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
var selectedBasemapTitle = e.AddedItems[0].ToString();
MainMapView.Map.Basemap = _basemapOptions[selectedBasemapTitle];
}
private void Menu_Full_Extent_OnClick(object sender, RoutedEventArgs e)
{
MainMapView.SetViewpointScaleAsync(192866676.56141916);
}
private void Menu_Wrap_Around_OnClick(object sender, RoutedEventArgs e)
{
if (Menu_Wrap_Around.Header.Equals("开启漫游"))
{
MainMapView.WrapAroundMode = Esri.ArcGISRuntime.UI.WrapAroundMode.EnabledWhenSupported;
Menu_Wrap_Around.Header = "关闭漫游";
}
else
{
MainMapView.WrapAroundMode = Esri.ArcGISRuntime.UI.WrapAroundMode.Disabled;
Menu_Wrap_Around.Header = "开启漫游";
}
}
private void Menu_Exit_OnClick(object sender, RoutedEventArgs e)
{
if (System.Windows.MessageBox.Show("确定退出?", "退出程序", MessageBoxButton.OKCancel, MessageBoxImage.Question) ==
MessageBoxResult.OK)
{
Application.Current.Shutdown();
}
}
private void Btn_Add_Online_OnClick(object sender, RoutedEventArgs e)
{
AddPrivateOnlineMap();
}
private async void AddPrivateOnlineMap()
{
Map map = new Map(BasemapStyle.ArcGISTopographic);
// Create an ArcGIS Portal object.
ArcGISPortal portal = await ArcGISPortal.CreateAsync();
// Create a portal item from the ArcGIS Portal object using a portal item string.
PortalItem portalItem = await PortalItem.CreateAsync(portal, "29d7c59212ef479995f5b42bacc9de4c");
FeatureLayer featureLayer = new FeatureLayer(portalItem, 0);
map.OperationalLayers.Add(featureLayer);
MainMapView.Map = map;
AddLayerNameToList();
}
private async void MainMapView_OnGeoViewTapped(object? sender, GeoViewInputEventArgs e)
{
MainMapView.DismissCallout();
if (m_CurOper == CURRENTOPERATION.NullOpe)
{
MapPoint mapLocation = e.Location;
Geometry myGeometry = mapLocation.Project(SpatialReferences.Wgs84);
MapPoint projectedLocation = (MapPoint)myGeometry;
string mapLocationDescription =
string.Format("纬度: {0:F3} 经度:{1:F3}", projectedLocation.Y, projectedLocation.X);
CalloutDefinition myCalloutDefinition = new CalloutDefinition("当前位置:", mapLocationDescription);
MainMapView.ShowCalloutAt(mapLocation, myCalloutDefinition);
}
else if (m_CurOper == CURRENTOPERATION.SelectQuery)
{
if (MainMapView.Map.OperationalLayers.Count > 0)
{
FeatureLayer _featureLayer = MainMapView.Map.OperationalLayers.First() as FeatureLayer;
if (_featureLayer != null)
{
FunClickQuery(e.Location, _featureLayer);
}
}
}
else if (m_CurOper == CURRENTOPERATION.IdentifyQuery)
{
if (MainMapView.Map.OperationalLayers.Count > 0)
{
FeatureLayer _featureLayer = MainMapView.Map.OperationalLayers.First() as FeatureLayer;
if (_featureLayer != null)
{
FunIndentifyQuery(e.Position, _featureLayer);
}
}
}
else if (m_CurOper == CURRENTOPERATION.Cal_Buff)
{
IdentifyGraphicsOverlayResult gResult_Buff =
await MainMapView.IdentifyGraphicsOverlayAsync(_pGraphicsOverLay, e.Position, 5, false);
if (gResult_Buff.Graphics.Count < 1)
{
return;
}
Graphic selGraphic_Buff = gResult_Buff.Graphics.First();
selGraphic_Buff.IsSelected = true;
listOfClipGraphics.Add(selGraphic_Buff); //记录所选图形
if (listOfClipGraphics.Count == 1) //图形数目为1时进行缓冲计算
{
Graphic g1 = listOfClipGraphics[0];
Esri.ArcGISRuntime.Geometry.Geometry resultGeometry =
GeometryEngine.Buffer(g1.Geometry, 500000.0); //执行缓冲操作
if (resultGeometry != null) //处理结果
{
_pGraphicsOverLay.Graphics.Remove(g1); //从图形层中移除原图形
Graphic clipedGraphic = new Graphic(resultGeometry, new
SimpleFillSymbol(SimpleFillSymbolStyle.Solid, Color.FromArgb(125, 255, 250, 0), new
SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.FromArgb(0, 0, 0),
4.0))); //利用剪切结果构造新的图形
_pGraphicsOverLay.Graphics.Add(clipedGraphic);
m_CurOper = CURRENTOPERATION.NullOpe;
}
listOfClipGraphics.Clear(); //清空图形选择集合
_pGraphicsOverLay.ClearSelection(); //清空图形层所选
}
}
else if (m_CurOper == CURRENTOPERATION.Cal_Union)
{
Console.WriteLine("Inside the if condition");
IdentifyGraphicsOverlayResult gResultUnion = await
MainMapView.IdentifyGraphicsOverlayAsync(_pGraphicsOverLay, e.Position, 5, false);
if (gResultUnion.Graphics.Count < 1)
{
return;
}
Graphic selGraphicUnion = gResultUnion.Graphics.First(); //每次选中的Graphic取出来
selGraphicUnion.IsSelected = true;
listOfClipGraphics.Add(selGraphicUnion); //记录所选图形
if (listOfClipGraphics.Count == 2) //图形数目为2时进行剪切计算
{
Graphic g1 = listOfClipGraphics[0];
Graphic g2 = listOfClipGraphics[1];
if (g1.Geometry.GeometryType != GeometryType.Polygon ||
g2.Geometry.GeometryType != GeometryType.Polygon) //如果所选图形不是多边形,则退出
{
MessageBox.Show("请选择两个多边形图形!");
listOfClipGraphics.Clear();
_pGraphicsOverLay.ClearSelection();
return;
}
Esri.ArcGISRuntime.Geometry.Geometry resultGeometry =
GeometryEngine.Union(g1.Geometry, g2.Geometry); //执行联合操作
if (resultGeometry != null) //处理结果
{
_pGraphicsOverLay.Graphics.Remove(g1); //从图形层中移除原图形
_pGraphicsOverLay.Graphics.Remove(g2);
Graphic clipedGraphic = new Graphic(resultGeometry, fillSymbol); //利用联合结果构建新的图形
_pGraphicsOverLay.Graphics.Add(clipedGraphic);
m_CurOper = CURRENTOPERATION.NullOpe;
}
listOfClipGraphics.Clear(); //清空图形选择集合
_pGraphicsOverLay.ClearSelection(); //清空图形层所选
}
}
else if (m_CurOper == CURRENTOPERATION.Cal_Cut)
{
IdentifyGraphicsOverlayResult gResult_Cut = await
MainMapView.IdentifyGraphicsOverlayAsync(_pGraphicsOverLay, e.Position, 5, false);
if (gResult_Cut.Graphics.Count < 1)
{
return;
}
Graphic selGraphic_Cut = gResult_Cut.Graphics.First();
selGraphic_Cut.IsSelected = true;
listOfClipGraphics.Add(selGraphic_Cut); //记录所选图形
if (listOfClipGraphics.Count == 2) //图形数目为1时进行剪切计算
{
Graphic g1 = listOfClipGraphics[0];
Graphic g2 = listOfClipGraphics[1];
if (g1.Geometry.GeometryType != GeometryType.Polygon ||
g2.Geometry.GeometryType != GeometryType.Polyline) //如果所选图形不是多边形,则退出
{
MessageBox.Show("请先选择一个面要素后再选择一个线要素.");
listOfClipGraphics.Clear();
_pGraphicsOverLay.ClearSelection();
return;
}
Esri.ArcGISRuntime.Geometry.Polyline polyLine =
(Esri.ArcGISRuntime.Geometry.Polyline)g2.Geometry;
Esri.ArcGISRuntime.Geometry.Geometry[] resultGeometry =
GeometryEngine.Cut(g1.Geometry, polyLine); //执行剪切操作
if (resultGeometry != null) //处理结果
{
_pGraphicsOverLay.Graphics.Remove(g1);
_pGraphicsOverLay.Graphics.Remove(g2);
for (int z = 0; z < resultGeometry.Length; z++)
{
Graphic clipedGraphic = new Graphic(resultGeometry[z],
fillSymbol); //利 用剪切结果构建新的图形
_pGraphicsOverLay.Graphics.Add(clipedGraphic);
}
m_CurOper = CURRENTOPERATION.NullOpe;
}
listOfClipGraphics.Clear(); //清空图形选择集合
_pGraphicsOverLay.ClearSelection(); //清空图形层所选
}
}else if (m_CurOper == CURRENTOPERATION.Cal_Intersection)
{
IdentifyGraphicsOverlayResult gResult_Intersect = await MainMapView.IdentifyGraphicsOverlayAsync(_pGraphicsOverLay, e.Position, 5, false);
if (gResult_Intersect.Graphics.Count < 1)
return;
Graphic selGraphic_Intersect = gResult_Intersect.Graphics.First();
selGraphic_Intersect.IsSelected = true;
listOfClipGraphics.Add(selGraphic_Intersect); //记录所选图形
if (listOfClipGraphics.Count == 2) //图形数目为2时进行求交计算
{
Graphic g1 = listOfClipGraphics[0];
Graphic g2 = listOfClipGraphics[1];
IReadOnlyList<Geometry> resultGeometry = GeometryEngine.Intersections(g1.Geometry, g2.Geometry); //执行求交点操作
// Geometry resultGeometry = GeometryEngine.Intersection(g1.Geometry, g2.Geometry); //执行求交操作
if (resultGeometry != null) //处理结果
{
_pGraphicsOverLay.Graphics.Remove(g1);
_pGraphicsOverLay.Graphics.Remove(g2);
foreach (var pointGeometry in resultGeometry)
{
Graphic clipedGraphic = new Graphic(pointGeometry, pointSymbol); //利用求交结果构建新的图形
_pGraphicsOverLay.Graphics.Add(clipedGraphic);
}
m_CurOper = CURRENTOPERATION.NullOpe;
}
listOfClipGraphics.Clear();//清空图形选择集合
_pGraphicsOverLay.ClearSelection();//清空图形层所选
}
}else if (m_CurOper == CURRENTOPERATION.Cal_Intersect)
{
IdentifyGraphicsOverlayResult gResult_Intersect = await MainMapView.IdentifyGraphicsOverlayAsync(_pGraphicsOverLay, e.Position, 5, false);
if (gResult_Intersect.Graphics.Count < 1)
return;
Graphic selGraphic_Intersect = gResult_Intersect.Graphics.First();
selGraphic_Intersect.IsSelected = true;
listOfClipGraphics.Add(selGraphic_Intersect); //记录所选图形
if (listOfClipGraphics.Count == 2) //图形数目为2时进行求交计算
{
Graphic g1 = listOfClipGraphics[0];
Graphic g2 = listOfClipGraphics[1];
// IReadOnlyList<Geometry> resultGeometry = GeometryEngine.Intersections(g1.Geometry, g2.Geometry); //执行求交点操作
Geometry resultGeometry = GeometryEngine.Intersection(g1.Geometry, g2.Geometry); //执行求交操作
if (resultGeometry != null) //处理结果
{
_pGraphicsOverLay.Graphics.Remove(g1);
_pGraphicsOverLay.Graphics.Remove(g2);
Graphic clipedGraphic = new Graphic(resultGeometry, pointSymbol); //利用求交结果构建新的图形
_pGraphicsOverLay.Graphics.Add(clipedGraphic);
m_CurOper = CURRENTOPERATION.NullOpe;
}
listOfClipGraphics.Clear();//清空图形选择集合
_pGraphicsOverLay.ClearSelection();//清空图形层所选
}
}else if (m_CurOper == CURRENTOPERATION.Cal_Clip)
{
IdentifyGraphicsOverlayResult gResult_Intersect = await MainMapView.IdentifyGraphicsOverlayAsync(_pGraphicsOverLay, e.Position, 5, false);
if (gResult_Intersect.Graphics.Count < 1)
return;
Graphic selGraphic_Intersect = gResult_Intersect.Graphics.First();
selGraphic_Intersect.IsSelected = true;
listOfClipGraphics.Add(selGraphic_Intersect); //记录所选图形
if (listOfClipGraphics.Count == 2) //图形数目为2时进行求交计算
{
Graphic g1 = listOfClipGraphics[0];
Graphic g2 = listOfClipGraphics[1];
Geometry resultGeometry = GeometryEngine.Clip(g1.Geometry, g2.Geometry.Extent); //执行求交操作
if (resultGeometry != null) //处理结果
{
_pGraphicsOverLay.Graphics.Remove(g1);
_pGraphicsOverLay.Graphics.Remove(g2);
Graphic clipedGraphic = new Graphic(resultGeometry, fillSymbol); //利用求交结果构建新的图形
_pGraphicsOverLay.Graphics.Add(clipedGraphic);
m_CurOper = CURRENTOPERATION.NullOpe;
}
listOfClipGraphics.Clear();//清空图形选择集合
_pGraphicsOverLay.ClearSelection();//清空图形层所选
}
}else if (m_CurOper == CURRENTOPERATION.Cal_Simplify)
{
IdentifyGraphicsOverlayResult gResult_Buff =
await MainMapView.IdentifyGraphicsOverlayAsync(_pGraphicsOverLay, e.Position, 5, false);
if (gResult_Buff.Graphics.Count < 1)
{
return;
}
Graphic selGraphic_Buff = gResult_Buff.Graphics.First();
selGraphic_Buff.IsSelected = true;
listOfClipGraphics.Add(selGraphic_Buff); //记录所选图形
if (listOfClipGraphics.Count == 1) //图形数目为1时进行缓冲计算
{
Graphic g1 = listOfClipGraphics[0];
Esri.ArcGISRuntime.Geometry.Geometry resultGeometry =
GeometryEngine.Simplify(g1.Geometry); //执行缓冲操作
if (resultGeometry != null) //处理结果
{
_pGraphicsOverLay.Graphics.Remove(g1); //从图形层中移除原图形
if(resultGeometry.GeometryType == GeometryType.Point || resultGeometry.GeometryType == GeometryType.Multipoint){
Graphic simplifiedGraphic = new Graphic(resultGeometry, pointSymbol); //利用剪切结果构造新的图形
_pGraphicsOverLay.Graphics.Add(simplifiedGraphic);
}else if (resultGeometry.GeometryType == GeometryType.Polyline)
{
Graphic simplifiedGraphic = new Graphic(resultGeometry, lineSymbol); //利用剪切结果构造新的图形
_pGraphicsOverLay.Graphics.Add(simplifiedGraphic);
}else if (resultGeometry.GeometryType == GeometryType.Polygon)
{
Graphic simplifiedGraphic = new Graphic(resultGeometry, fillSymbol); //利用剪切结果构造新的图形
_pGraphicsOverLay.Graphics.Add(simplifiedGraphic);
}
m_CurOper = CURRENTOPERATION.NullOpe;
}
listOfClipGraphics.Clear(); //清空图形选择集合
_pGraphicsOverLay.ClearSelection(); //清空图形层所选
}
}
}
private void Menu_Simple_Identify_OnClick(object sender, RoutedEventArgs e)
{
string sQueryFieldName = "Name";
string stateName = "New York";
FeatureLayer _featureLayer = MainMapView.Map.OperationalLayers[0] as FeatureLayer;
if (_featureLayer != null)
{
QueryStateFeature3(_featureLayer, sQueryFieldName, stateName);
}
}
private async Task QueryStateFeature3(FeatureLayer _featureLayer, string sQueryFieldName, string stateName)
{
try
{
QueryParameters pQueryP = new QueryParameters();
string sformat = stateName.Trim().ToUpper();
pQueryP.WhereClause = "upper(" + sQueryFieldName + ") LIKE '%" + sformat + "%'";
await _featureLayer.SelectFeaturesAsync(pQueryP, Esri.ArcGISRuntime.Mapping.SelectionMode.New);
FeatureQueryResult pQueryResult = await _featureLayer.GetSelectedFeaturesAsync();
List<Feature> pListFeatures = pQueryResult.ToList();
EnvelopeBuilder pEnvBuilder = new EnvelopeBuilder(_featureLayer.SpatialReference);
for (int i = 0; i < pListFeatures.Count; i++)
{
pEnvBuilder.UnionOf(pListFeatures[i].Geometry.Extent);
}
await MainMapView.SetViewpointGeometryAsync(pEnvBuilder.ToGeometry(), 50);
}
catch (Exception ex)
{
System.Windows.MessageBox.Show("【程序出错】" + ex.Message);
}
}
private async void FunClickQuery(MapPoint pPoint, FeatureLayer _featureLayer)
{
double tol = 3; //容差设为3像素
double mapTol = tol * MainMapView.UnitsPerPixel;
MapPoint pNormalPoint = pPoint;
if (MainMapView.IsWrapAroundEnabled)
{
pNormalPoint = (MapPoint)GeometryEngine.NormalizeCentralMeridian(pPoint);
}
Envelope selEnv = new Envelope(pNormalPoint.X - mapTol, pNormalPoint.Y - mapTol, pNormalPoint.X + mapTol,
pNormalPoint.Y + mapTol, MainMapView.SpatialReference);
QueryParameters pQueryPara = new QueryParameters();
pQueryPara.Geometry = selEnv;
pQueryPara.SpatialRelationship = SpatialRelationship.Intersects;
await _featureLayer.SelectFeaturesAsync(pQueryPara, Esri.ArcGISRuntime.Mapping.SelectionMode.New);
FeatureQueryResult pQueryResult = await _featureLayer.GetSelectedFeaturesAsync();
List<Feature> pListFeatures = pQueryResult.ToList();
if (pListFeatures.Count <= 0)
{
return;
}
EnvelopeBuilder pEnvBuilder = new EnvelopeBuilder(_featureLayer.SpatialReference);
for (int i = 0; i < pListFeatures.Count; i++)
{
pEnvBuilder.UnionOf(pListFeatures[i].Geometry.Extent);
}
await MainMapView.SetViewpointGeometryAsync(pEnvBuilder.ToGeometry(), 50);
Feature pFeature;
string sInfo = "";
IReadOnlyList<Field> pFields = pQueryResult.Fields;
for (int i = 0; i < pListFeatures.Count; i++)
{
pFeature = pListFeatures[i];
IDictionary<string, object> FeatureAttri = pFeature.Attributes;
string str;
object obj;
sInfo += "选中的第" + i.ToString() + "个要素的属性\n\r";
for (int j = 0; j < FeatureAttri.Count; j++)
{
str = FeatureAttri.Keys.ElementAt(j);
obj = FeatureAttri.Values.ElementAt(j);
sInfo += str + ":" + obj.ToString() + "\r\n";
}
MessageBox.Show(sInfo);
}
}
private async void FunIndentifyQuery(System.Windows.Point pPoint, FeatureLayer pFLayer)
{
IdentifyLayerResult identifyLayerResult = await MainMapView.IdentifyLayerAsync(pFLayer, pPoint, 20, false);
if (!identifyLayerResult.GeoElements.Any())
{
return;
}
Feature identifyFeature = (Feature)identifyLayerResult.GeoElements.First();
IDictionary<string, object> FeatureAttri = identifyFeature.Attributes;
string str;
string tempStr = "";
object obj;
for (int i = 0; i < FeatureAttri.Count; i++)
{
str = FeatureAttri.Keys.ElementAt(i);
obj = FeatureAttri.Values.ElementAt(i);
tempStr += str + ":" + obj.ToString() + "\r\n";
}
System.Windows.MessageBox.Show(tempStr);
}
private void Menu_Click_Indentify_OnClick(object sender, RoutedEventArgs e)
{
m_CurOper = CURRENTOPERATION.SelectQuery;
}
private void Menu_Identify_Indentify_OnClick(object sender, RoutedEventArgs e)
{
m_CurOper = CURRENTOPERATION.IdentifyQuery;
}
private void Menu_OpenRaster_OnClick(object sender, RoutedEventArgs e)
{
OpenRaster();
}
private async void OpenRaster()
{
var aMap = new Map(BasemapStyle.ArcGISImagery);
await aMap.LoadAsync();
string _slocalRasterPath = "";
System.Windows.Forms.OpenFileDialog fileDialog = new System.Windows.Forms.OpenFileDialog();
fileDialog.Filter = "栅格文件(*.tif)|*.tif";
if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
_slocalRasterPath = fileDialog.FileName;
}
if (System.IO.File.Exists(_slocalRasterPath))
{
Raster raster = new Raster(_slocalRasterPath);
RasterLayer rasterLayer = new RasterLayer(raster);
aMap.OperationalLayers.Add(rasterLayer);
await rasterLayer.LoadAsync();
Viewpoint geodatabaseViewPoint = new Viewpoint(rasterLayer.FullExtent);
aMap.InitialViewpoint = geodatabaseViewPoint;
MainMapView.Map = aMap;
}
AddLayerNameToList();
}
private void LayerListBox_OnPreviewMouseMove(object sender, MouseEventArgs e)
{
if (e.LeftButton == System.Windows.Input.MouseButtonState.Pressed)
{
var pos = e.GetPosition(LayerListBox);
if (pos.X < 20) return;
System.Windows.Media.HitTestResult result =
System.Windows.Media.VisualTreeHelper.HitTest(LayerListBox, pos);
if (result == null) return;
var listBoxItem = Utils.FindVisualParent<ListBoxItem>(result.VisualHit);
if (listBoxItem == null) return;
DataObject dataObj = new DataObject(listBoxItem.Content as CheckBox);
DragDrop.DoDragDrop(LayerListBox, listBoxItem, DragDropEffects.Move);
}
}
private void LayerListBox_OnDrop(object sender, DragEventArgs e)
{
var pos = e.GetPosition(sender as ListBox);
var result = System.Windows.Media.VisualTreeHelper.HitTest(LayerListBox, pos);
if (result == null)
{
return;
}
var sourceItem = e.Data.GetData(typeof(ListBoxItem)) as ListBoxItem;
// var sourcePerson = sourceItem.Content;
if (sourceItem == null)
{
return;
}
var listBoxItem = Utils.FindVisualParent<ListBoxItem>(result.VisualHit);
if (listBoxItem == null)
{
return;
}
var targetPerson = listBoxItem.Content as CheckBox;
if (ReferenceEquals(listBoxItem, sourceItem))
{
return;
}
int targetIndex = LayerListBox.Items.IndexOf(listBoxItem);
int sourceIndex = LayerListBox.Items.IndexOf(sourceItem);
LayerListBox.Items.Remove(sourceItem);
LayerListBox.Items.Insert(targetIndex, sourceItem);
MoveLayer(sourceItem.ToolTip as string, listBoxItem.ToolTip as string);
}
private void AddLayerNameToList()
{
LayerListBox.Items.Clear();
LayerListBox.AllowDrop = true;
LayerCollection pLayers = MainMapView.Map.OperationalLayers;
if (pLayers.Count <= 0) return;
List<CheckBox> checkBoxes = new List<CheckBox>();
for (int i = pLayers.Count - 1; i >= 0; i--)
{
CheckBox cb = new CheckBox()
{
Margin = new Thickness()
{
Left = 0,
Top = 5,
Right = 0,
Bottom = 5
}
};
Console.WriteLine(pLayers[i].Name);
cb.Content = pLayers[i].Name;
cb.ToolTip = cb.Content;
cb.Name = pLayers[i].Name;
cb.IsChecked = true;
cb.Focusable = false;
cb.Checked += new RoutedEventHandler(Checked_Layers_CheckBox);
cb.Unchecked += new RoutedEventHandler(UnChecked_Layers_CheckBox);
ListBoxItem listBoxItem = new ListBoxItem();
listBoxItem.Content = cb;
listBoxItem.ToolTip = pLayers[i].Name;
LayerListBox.Items.Add(listBoxItem);
}
}
private void UnChecked_Layers_CheckBox(object sender, RoutedEventArgs e)
{
CheckBox cb = sender as CheckBox;
cb.IsChecked = false;
int index = GetLayerIndex(cb.ToolTip as string);
MainMapView.Map.OperationalLayers[index].IsVisible = false;
}
private void Checked_Layers_CheckBox(object sender, RoutedEventArgs e)
{
CheckBox cb = sender as CheckBox;
cb.IsChecked = true;
int index = GetLayerIndex(cb.ToolTip as string);
MainMapView.Map.OperationalLayers[index].IsVisible = true;
}
internal static class Utils
{
public static T FindVisualParent<T>(DependencyObject obj) where T : class
{
while (obj != null)
{
if (obj is T)
return obj as T;
obj = System.Windows.Media.VisualTreeHelper.GetParent(obj);
}
return null;
}
}
private Layer GetLayer(string name)
{
LayerCollection pLayers = MainMapView.Map.OperationalLayers;
for (int i = pLayers.Count - 1; i >= 0; i--)
{
if (pLayers[i].Name.Equals(name))
{
return pLayers[i];
}
}
return null;
}
private void MoveLayer(string sourceLayer, string targetLayer)
{
LayerCollection pLayers = MainMapView.Map.OperationalLayers;
Layer sourcLayer = GetLayer(sourceLayer);
pLayers.Remove(sourcLayer);
int targerIndex = GetLayerIndex(targetLayer);
}
private int GetLayerIndex(string name)
{
LayerCollection pLayers = MainMapView.Map.OperationalLayers;
for (int i = pLayers.Count - 1; i >= 0; i--)
{
if (pLayers[i].Name.Equals(name))
{
return i;
}
}
return -1;
}
private void Menu_Point_Symbol_Click(object sender, RoutedEventArgs e)
{
MainMapView.GraphicsOverlays[0].Graphics.Clear();
m_CurOper = CURRENTOPERATION.DrawPoint;
}
private async void MainMapView_OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
IInputElement mv = (IInputElement)sender;
MapPoint location = MainMapView.ScreenToLocation(e.GetPosition(mv));
if (m_CurOper == CURRENTOPERATION.DrawPoint)
{
Graphic gPT = new Graphic(location, pointSymbol);
MainMapView.GraphicsOverlays[0].Graphics.Add(gPT);
}
else if (m_CurOper == CURRENTOPERATION.DrawLine)
{
linePoints.Add(location);
if (linePoints.Count > 1)
{
if (linesList.Count > 0)
{
Graphic curGraphic = linesList[linesList.Count - 1];
MainMapView.GraphicsOverlays[0].Graphics.Remove(curGraphic);
linesList.Remove(curGraphic);
}
Polyline line = new Polyline(linePoints);
Graphic lineGraphic = new Graphic(line, lineSymbol);
MainMapView.GraphicsOverlays[0].Graphics.Add(lineGraphic);
linesList.Add(lineGraphic);
}
}
else if (m_CurOper == CURRENTOPERATION.DrawPolygon)
{
linePoints.Add(location);
if (linePoints.Count > 1)
{
if (linesList.Count > 0)
{
Graphic curGraphic = linesList[linesList.Count - 1];
MainMapView.GraphicsOverlays[0].Graphics.Remove(curGraphic);
linesList.Remove(curGraphic);
}
Polygon polygon = new Polygon(linePoints);
Graphic polygonGraphic = new Graphic(polygon, fillSymbol);
MainMapView.GraphicsOverlays[0].Graphics.Add(polygonGraphic);
Polyline line = new Polyline(linePoints);
Graphic lineGraphic = new Graphic(line, lineSymbol);
// MainMapView.GraphicsOverlays[0].Graphics.Add(lineGraphic);
linesList.Add(lineGraphic);
}
}
if(m_CurOper == CURRENTOPERATION.ClickQuery)//检查是否为按照位置查询中的点选
{
IInputElement ie = (IInputElement)sender;//转换事件宿主对象为IInputElement对象
IReadOnlyList< IdentifyLayerResult> results =await
MainMapView.IdentifyLayersAsync(e.GetPosition(ie), 15, false);//根据鼠标点在所有图层中进行查询
if(results!=null)//查询结果不为空
{
if (locationQueryResultsWindow != null &&
locationQueryResultsWindow.IsClosed)//位置查询结果子窗体已关闭
{
locationQueryResultsWindow = null;//将子窗体对象置为空
}
if (locationQueryResultsWindow == null)
{
locationQueryResultsWindow = new LocationQueryResultsWindow();//构造新的子窗体对象
}
locationQueryResultsWindow.ResultCollection = results;//为子窗体引用查询结果集对象
locationQueryResultsWindow.Show();//显示该子窗体
locationQueryResultsWindow.Activate();//使子窗体处于激活状态
}
}
else if (m_CurOper == CURRENTOPERATION.ExtentQuery)
{
if (_startLocation == null)
{
MainMapView.GraphicsOverlays.Clear();
this._startLocation = location;
}
else
{
MapPoint _curLocation = location;
List<MapPoint> extentPoints = new List<MapPoint>();
extentPoints.Add(new MapPoint(_startLocation.X, _startLocation.Y));
extentPoints.Add(new MapPoint(_startLocation.X, location.Y));
extentPoints.Add(new MapPoint(location.X, location.Y));
extentPoints.Add(new MapPoint(location.X, _startLocation.Y));
Polygon polygon = new Polygon(extentPoints);
Color lineColor = Color.FromArgb(255, 255, 0, 0);
SimpleLineSymbol lineSymbol =
new Esri.ArcGISRuntime.Symbology.SimpleLineSymbol(SimpleLineSymbolStyle.Dash, lineColor, 2.0);
Color fillColor = Color.FromArgb(0, 0, 0, 0);
SimpleFillSymbol fillSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle.Solid, fillColor, lineSymbol);
Graphic polygonGraphic = new Graphic(polygon, fillSymbol);
MainMapView.GraphicsOverlays.Add(new GraphicsOverlay());
MainMapView.GraphicsOverlays[0].Graphics.Add(polygonGraphic);
Envelope selEnv = new Envelope(this._startLocation.X, this._startLocation.Y, location.X,
location.Y, MainMapView.SpatialReference);
QueryParameters pQueryPara = new QueryParameters();
pQueryPara.Geometry = selEnv;
pQueryPara.SpatialRelationship = SpatialRelationship.Intersects;
// _featureLayer = MainMapView.Map.OperationalLayers[0] as FeatureLayer;
List<QueryResult> queryResults = new List<QueryResult>();
foreach (FeatureLayer featureLayer in MainMapView.Map.OperationalLayers)
{
await featureLayer.SelectFeaturesAsync(pQueryPara,
Esri.ArcGISRuntime.Mapping.SelectionMode.New);
FeatureQueryResult pQueryResult = await featureLayer.GetSelectedFeaturesAsync();
List<Feature> pListFeatures = pQueryResult.ToList();
if (pListFeatures.Count <= 0)
{
return;
}
EnvelopeBuilder pEnvBuilder = new EnvelopeBuilder(featureLayer.SpatialReference);
for (int i = 0; i < pListFeatures.Count; i++)
{
pEnvBuilder.UnionOf(pListFeatures[i].Geometry.Extent);
}
await MainMapView.SetViewpointGeometryAsync(pEnvBuilder.ToGeometry(), 50);
Feature pFeature;
string sInfo = "";
IReadOnlyList<Field> pFields = pQueryResult.Fields;
string featureLayerName = featureLayer.Name;
List<IDictionary<string, object>> attributes = new List<IDictionary<string, object>>();
for (int i = 0; i < pListFeatures.Count; i++)
{
pFeature = pListFeatures[i];
IDictionary<string, object> FeatureAttri = pFeature.Attributes;
string featureName = pFeature.FeatureTable.Layer.Name;
attributes.Add(FeatureAttri);
}
queryResults.Add(new QueryResult(featureLayerName, attributes));
}
ExtentLocationQueryResultsWindow resultsWindow = new ExtentLocationQueryResultsWindow();
resultsWindow.resultCollection = queryResults;
resultsWindow.Show();
resultsWindow.Activate();
MainMapView.GraphicsOverlays.Clear();
_startLocation = null;
}
}
}
private void Menu_Layers_Options_OnClick(object sender, RoutedEventArgs e)
{
OptionsWindow op = new OptionsWindow();
op.PointSymbol = pointSymbol;
op.LineSymbol = lineSymbol;
op.FillSymbol = fillSymbol;
op.GeometryType = MainMapView.GraphicsOverlays[0].Graphics[0].Geometry.GeometryType;
op.ShowDialog();
}
private void Menu_Point_Draw_Line_OnClick(object sender, RoutedEventArgs e)
{
MainMapView.GraphicsOverlays[0].Graphics.Clear();
m_CurOper = CURRENTOPERATION.DrawLine;
linePoints.Clear();
}
private void Menu_Point_Draw_Polygon_OnClick(object sender, RoutedEventArgs e)
{
MainMapView.GraphicsOverlays[0].Graphics.Clear();
m_CurOper = CURRENTOPERATION.DrawPolygon;
linePoints.Clear();
}
private void MainMapView_OnMouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
m_CurOper = CURRENTOPERATION.NullOpe;
}
private void SetSimpleRender(FeatureLayer pLayer, Symbol pSymbol)
{
if (pSymbol == null)
{
pSymbol = this.pSymbol;
}
Random r = new Random();
int num = r.Next(0, 20);
Color pColor = ColorArray[num];
OptionsWindow op = new OptionsWindow();
if (pSymbol == null)
{
if (pLayer.FeatureTable.GeometryType == GeometryType.Point ||
pLayer.FeatureTable.GeometryType == GeometryType.Multipoint)
{
pSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Circle, pColor, 5);
op.PointSymbol = (SimpleMarkerSymbol)pSymbol;
}
else if (pLayer.FeatureTable.GeometryType == GeometryType.Polyline)
{
pSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, pColor, 1);
op.LineSymbol = (SimpleLineSymbol)pSymbol;
}
else if (pLayer.FeatureTable.GeometryType == GeometryType.Polygon)
{
SimpleLineSymbol pOutlineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.Gray, 1);
pSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle.Solid, pColor, pOutlineSymbol);
op.FillSymbol = (SimpleFillSymbol)pSymbol;
}
}
else
{
if (pLayer.FeatureTable.GeometryType == GeometryType.Point ||
pLayer.FeatureTable.GeometryType == GeometryType.Multipoint)
{
op.PointSymbol = (SimpleMarkerSymbol)pSymbol;
}
else if (pLayer.FeatureTable.GeometryType == GeometryType.Polyline)
{
op.LineSymbol = (SimpleLineSymbol)pSymbol;
}
else if (pLayer.FeatureTable.GeometryType == GeometryType.Polygon)
{
op.FillSymbol = (SimpleFillSymbol)pSymbol;
}
}
SimpleRenderer sRenderer = new SimpleRenderer(pSymbol);
pLayer.Renderer = sRenderer;
op.GeometryType = pLayer.FeatureTable.GeometryType;
op.ShowDialog();
}
private void Menu_Simple_Color_OnClick(object sender, RoutedEventArgs e)
{
FeatureLayer _featureLayer = MainMapView.Map.OperationalLayers[0] as FeatureLayer;
SetSimpleRender(_featureLayer, pSymbol);
}
private async void SetUniqueRender(FeatureLayer pLayer, string sFieldName, List<Symbol> pSymbolList = null)
{
UniqueValueRenderer regionRenderer = new UniqueValueRenderer();
regionRenderer.FieldNames.Add(sFieldName);
QueryParameters pQueryPara = new QueryParameters();
pQueryPara.WhereClause = "1=1";
FeatureQueryResult queryResult = await pLayer.FeatureTable.QueryFeaturesAsync(pQueryPara);
IEnumerator<Feature> queryFeatures = queryResult.GetEnumerator();
object featureValue;
int i = 0;
while (queryFeatures.MoveNext())
{
featureValue = queryFeatures.Current.GetAttributeValue(sFieldName);
Symbol tempSymbol = null;
if (pSymbolList == null)
{
if (i >= ColorArray.Count)
i = 0;
Color pColor = ColorArray[i];
if (pLayer.FeatureTable.GeometryType == GeometryType.Point ||
pLayer.FeatureTable.GeometryType == GeometryType.Multipoint)
{
tempSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Circle, pColor, 5);
}
else if (pLayer.FeatureTable.GeometryType == GeometryType.Polyline)
{
tempSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, pColor, 1);
}
else if (pLayer.FeatureTable.GeometryType == GeometryType.Polygon)
{
SimpleLineSymbol tempSymbol2 = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid,
Color.Gray, 1);
tempSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle.Solid, pColor, tempSymbol2);
}
}
else
{
tempSymbol = pSymbolList[i];
}
i++;
UniqueValue pUniqueValue = new UniqueValue("null", "null", tempSymbol, featureValue);
regionRenderer.UniqueValues.Add(pUniqueValue);
}
SimpleFillSymbol defaultFillSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle.Cross, Color.Gray,
null);
regionRenderer.DefaultSymbol = defaultFillSymbol;
regionRenderer.DefaultLabel = "Other";
pLayer.Renderer = regionRenderer;
}
private void Menu_Unique_Color_OnClick(object sender, RoutedEventArgs e)
{
if (MainMapView.Map.OperationalLayers.Count > 0)
{
FeatureLayer _featureLayer = MainMapView.Map.OperationalLayers[0] as FeatureLayer;
string sQueryFieldName = "XZQMC";
SetUniqueRender(_featureLayer, sQueryFieldName);
}
}
private async void SetClassBreaksRender(FeatureLayer pLayer, string sFieldName, int ClassifyCount = 5,
List<Symbol> pSymbolList = null)
{
//ClassBreaksRenderer
ClassBreaksRenderer pCBRenderer = new ClassBreaksRenderer();
//设置字段名
pCBRenderer.FieldName = sFieldName;
//设置统计查询条件,
StatisticDefinition statDefinitionMin = new StatisticDefinition(sFieldName, StatisticType.Minimum, "");
StatisticDefinition statDefinitionMax = new StatisticDefinition(sFieldName, StatisticType.Maximum, "");
List<StatisticDefinition> statDefinitions = new List<StatisticDefinition>
{
statDefinitionMin,
statDefinitionMax,
};
StatisticsQueryParameters pQueryPara = new StatisticsQueryParameters(statDefinitions);
//执行统计查询
StatisticsQueryResult queryResult = await pLayer.FeatureTable.QueryStatisticsAsync(pQueryPara);
//从统计结果中获取最大值,获取最小值
string str;
object max = null, min = null;
double dMax, dMin;
//获取该字段的最大值,最小值,为后续分级做准备
IReadOnlyDictionary<string, object> sResult = queryResult.First().Statistics;
for (int i = 0; i < sResult.Count; i++)
{
str = sResult.Keys.ElementAt(i);
if (str.Contains("MAX"))
max = sResult.Values.ElementAt(i);
if (str.Contains("MIN"))
min = sResult.Values.ElementAt(i);
}
dMax = (double)(max);
dMin = (double)(min);
//计算并设置分级中每一级别的范围,以及符号
for (int i = 0; i < ClassifyCount; i++)
{
ClassBreak pClassBreak = new ClassBreak();
//每一级别范围的最大值、最小值
if (i == 0)
pClassBreak.MinValue = dMin;
else
pClassBreak.MinValue = dMin + (dMax - dMin) * (i - 1) / ClassifyCount;
;
pClassBreak.MaxValue = dMin + (dMax - dMin) * (i + 1) / ClassifyCount;
Color tempColor = Color.FromArgb(i * 50 + 10, 255, 255);
//创建符号,这里图层为面层,直接创建面符号,注意若图层为 点层、线层,需创建对应的点符号、线符号
SimpleLineSymbol tempSymbol2 = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.Gray,
1);
Symbol pSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle.Solid, tempColor, tempSymbol2);
pClassBreak.Symbol = pSymbol;
//将设置好的ClassBreak放入ClassBreaksRenderer中。
pCBRenderer.ClassBreaks.Add(pClassBreak);
}
//将创建好的ClassBreaksRenderer 赋值给图层
pLayer.Renderer = pCBRenderer;
}
private void Menu_Level_Color_OnClick(object sender, RoutedEventArgs e)
{
if (MainMapView.Map.OperationalLayers.Count > 0)
{
FeatureLayer _featureLayer = MainMapView.Map.OperationalLayers[0] as FeatureLayer;
string sQueryFieldName = "FID";
SetClassBreaksRender(_featureLayer, sQueryFieldName);
}
}
private void Context_Menu_Delete_OnClick(object sender, RoutedEventArgs e)
{
Layer_Popup.IsOpen = false;
LayerListBox.Items.Remove(cur_LayerItem);
LayerCollection pLayers = MainMapView.Map.OperationalLayers;
Layer delLayer = GetLayer(cur_LayerItem.ToolTip as string);
pLayers.Remove(delLayer);
e.Handled = true;
}
private void LayerListBox_OnPreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
Layer_Popup.IsOpen = false;
var pos = e.GetPosition(LayerListBox);
System.Windows.Media.HitTestResult
result = System.Windows.Media.VisualTreeHelper.HitTest(LayerListBox, pos);
if (result == null)
{
Layer_Popup.IsOpen = false;
return;
}
var listBoxItem = Utils.FindVisualParent<ListBoxItem>(result.VisualHit);
if (listBoxItem == null)
{
Layer_Popup.IsOpen = false;
return;
}
cur_LayerItem = listBoxItem;
Layer_Popup.HorizontalOffset = pos.X;
Layer_Popup.VerticalOffset = pos.Y;
Layer_Popup.IsOpen = true;
e.Handled = true;
}
private void Context_Menu_Fit_OnClick(object sender, RoutedEventArgs e)
{
Layer_Popup.IsOpen = false;
Layer fitLayer = GetLayer(cur_LayerItem.ToolTip as string);
MainMapView.SetViewpointGeometryAsync(fitLayer.FullExtent);
e.Handled = true;
}
private void Context_Menu_Symbology_OnClick(object sender, RoutedEventArgs e)
{
Layer_Popup.IsOpen = false;
Layer symbologyLayer = GetLayer(cur_LayerItem.ToolTip as string);
FeatureLayer _featureLayer = (FeatureLayer)symbologyLayer;
if (_featureLayer != null && _featureLayer.Renderer is SimpleRenderer simpleRenderer)
{
var symbol = simpleRenderer.Symbol;
SetSimpleRender((FeatureLayer)symbologyLayer, symbol);
}
else
{
pSymbol = null;
SetSimpleRender((FeatureLayer)symbologyLayer, null);
}
e.Handled = true;
}
private void LayerListBox_OnPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
var pos = e.GetPosition(Layer_Popup);
System.Windows.Media.HitTestResult
result = System.Windows.Media.VisualTreeHelper.HitTest(Layer_Popup, pos);
if (result == null)
{
Layer_Popup.IsOpen = false;
return;
}
var menuItem = Utils.FindVisualParent<MenuItem>(result.VisualHit);
if (menuItem == null)
{
Layer_Popup.IsOpen = false;
return;
}
// Layer_Popup.IsOpen = false;
e.Handled = false;
}
private void CBEditBegin_Checked(object sender, RoutedEventArgs e)
{
//设置部分按钮可以操作。
SketchModeComboBox.IsEnabled = true;
BtnDraw.IsEnabled = true;
// 获取_ pGraphicsOverLay ,用于放置图形元素
// Window w = Window.GetWindow(this);
// MyMapView = (MapView)w.FindName("MyMapView");
_pGraphicsOverLay = new GraphicsOverlay();
MainMapView.GraphicsOverlays.Add(_pGraphicsOverLay);
SketchModeComboBox.ItemsSource =
System.Enum.GetValues(typeof(SketchCreationMode));
SketchModeComboBox.SelectedIndex = 0;
//设置图形元素编辑的相关属性
SketchEditConfiguration config = MainMapView.SketchEditor.EditConfiguration;
if (config != null)
{
config.AllowVertexEditing = true;
config.ResizeMode = SketchResizeMode.Uniform;
config.AllowMove = true;
}
//设置 页面的DataContext为 SketchEditor
DataContext = MainMapView.SketchEditor;
}
private async void BtnDraw_Click(object sender, RoutedEventArgs e)
{
try
{
BtnCancel.IsEnabled = true;
BtnRedo.IsEnabled = true;
BtnUndo.IsEnabled = true;
BtnComplete.IsEnabled = true;
SketchCreationMode creationMode =
(SketchCreationMode)SketchModeComboBox.SelectedItem;
Esri.ArcGISRuntime.Geometry.Geometry geometry = await
MainMapView.SketchEditor.StartAsync(creationMode, true);
// Create and add a graphic from the geometry the user drew
// Graphic graphic = new Graphic (geometry);
Graphic graphic = CreateGraphic(geometry);
_pGraphicsOverLay.Graphics.Add(graphic);
BtnClear.IsEnabled = _pGraphicsOverLay.Graphics.Count > 0;
BtnEdit.IsEnabled = _pGraphicsOverLay.Graphics.Count > 0;
}
catch (TaskCanceledException) //当 点击 取消后,抛出代码运行异常 ,需要添加该行
{
// Ignore ... let the user cancel drawing
}
catch (Exception ex)
{
// Report exceptions
MessageBox.Show("Error drawing graphic shape: " + ex.Message);
}
}
private Graphic CreateGraphic(Esri.ArcGISRuntime.Geometry.Geometry geometry)
{
// Create a graphic to display the specified geometry
//若不设置符号,图形元素不显示。
Symbol symbol = null;
switch (geometry.GeometryType)
{
// Symbolize with a fill symbol
case GeometryType.Envelope:
case GeometryType.Polygon:
{
symbol = new SimpleFillSymbol()
{
Color = System.Drawing.Color.Red,
Style = SimpleFillSymbolStyle.Solid
};
break;
}
// Symbolize with a line symbol
case GeometryType.Polyline:
{
symbol = new SimpleLineSymbol()
{
Color = System.Drawing.Color.Red,
Style = SimpleLineSymbolStyle.Solid,
Width = 5d
};
break;
}
// Symbolize with a marker symbol
case GeometryType.Point:
case GeometryType.Multipoint:
{
symbol = new SimpleMarkerSymbol()
{
Color = System.Drawing.Color.Red,
Style = SimpleMarkerSymbolStyle.Circle,
Size = 15d
};
break;
}
}
// pass back a new graphic with the appropriate symbol
return new Graphic(geometry, symbol);
}
private async void BtnEdit_Click(object sender, RoutedEventArgs e)
{
try
{
Graphic editGraphic = await GetGraphicAsync();
if (editGraphic == null)
{
return;
}
// Let the user make changes to the graphic's geometry, await the result (updated geometry)
Esri.ArcGISRuntime.Geometry.Geometry newGeometry =
await MainMapView.SketchEditor.StartAsync(editGraphic.Geometry);
// Display the updated geometry in the graphic
editGraphic.Geometry = newGeometry;
}
catch (TaskCanceledException) //当 点击 取消后,抛出代码运行异常 ,需要添加该行
{
// Ignore ... let the user cancel drawing
}
catch (Exception ex)
{
// Report exceptions
MessageBox.Show("Error drawing graphic shape: " + ex.Message);
}
}
private async Task<Graphic> GetGraphicAsync()
{
//鼠标点击,获取点坐标对象
Geometry pMapPoint = await
MainMapView.SketchEditor.StartAsync(SketchCreationMode.Point, false);
//将点对象由地图坐标转换为屏幕坐标
Point scrPoint = MainMapView.LocationToScreen((MapPoint)pMapPoint);
//利用Indendify识别该点选中的图形元素
IReadOnlyList<IdentifyGraphicsOverlayResult> results = await
MainMapView.IdentifyGraphicsOverlaysAsync(scrPoint, 2, false);
//获取选中的第一个元素
Graphic graphic = null;
IdentifyGraphicsOverlayResult idResult = results.FirstOrDefault();
if (idResult != null && idResult.Graphics.Count > 0)
{
graphic = idResult.Graphics.FirstOrDefault();
}
return graphic;
}
private void BtnClear_Click(object sender, RoutedEventArgs e)
{
_pGraphicsOverLay.Graphics.Clear();
BtnClear.IsEnabled = false;
BtnEdit.IsEnabled = false;
}
private void Menu_Buffer_OnClick(object sender, RoutedEventArgs e)
{
m_CurOper = CURRENTOPERATION.Cal_Buff;
}
private void Menu_Union_OnClick(object sender, RoutedEventArgs e)
{
m_CurOper = CURRENTOPERATION.Cal_Union;
}
private void Menu_Cut_OnClick(object sender, RoutedEventArgs e)
{
m_CurOper = CURRENTOPERATION.Cal_Cut;
}
private void Menu_Intersection_Point_OnClick(object sender, RoutedEventArgs e)
{
m_CurOper = CURRENTOPERATION.Cal_Intersection;
}
private void Menu_Intersect_OnClick(object sender, RoutedEventArgs e)
{
m_CurOper = CURRENTOPERATION.Cal_Intersect;
}
private void Menu_Simplify_OnClick(object sender, RoutedEventArgs e)
{
m_CurOper = CURRENTOPERATION.Cal_Simplify;
}
private void Menu_Clip_OnClick(object sender, RoutedEventArgs e)
{
m_CurOper = CURRENTOPERATION.Cal_Clip;
}
private void Menu_Topology_OnClick(object sender, RoutedEventArgs e)
{
MessageBox.Show("此功能暂未实现");
}
private void Menu_Attribute_Query_OnClick(object sender, RoutedEventArgs e)
{
List<FeatureTable> myTables;
myTables = new List<FeatureTable>();
for(int i=0;i<MainMapView.Map.OperationalLayers.Count;i++)
{
FeatureLayer pFL = MainMapView.Map.OperationalLayers[i] as FeatureLayer;
if(pFL != null)
{
myTables.Add(pFL.FeatureTable);
}
}
AttributeQuery qw = new AttributeQuery();//创建新的查询窗体对象
qw.Tables.AddRange(myTables);//为窗体对象的表集合对象添加表集合
bool r =(bool) qw.ShowDialog();//以对话框方式显示该子窗体
}
private void Menu_Query_Point_OnClick(object sender, RoutedEventArgs e)
{
selByGeometryType = 1;//设置其值为1
m_CurOper = CURRENTOPERATION.ClickQuery;
}
private void Menu_Query_Envelope_OnClick(object sender, RoutedEventArgs e)
{
selByGeometryType = 2;//设置其值为2
m_CurOper = CURRENTOPERATION.ExtentQuery;
}
}
}