原文:
ArcGIS API for Silverlight 调用GP服务加载等值线图层
第二篇、Silverlight客户端调用GP服务
利用ArcGIS API for Silverlight实现GP服务调用,这里的雨量数据是通过一个WebService获取而来,主要信息是雨量站点的经纬度坐标值和某个时间段内的降雨量值三个主要字段。
以下是核心代码部分:
<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:esri="http://schemas.esri.com/arcgis/client/2009" xmlns:controlsToolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Toolkit" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk" x:Class="TestDZX.MainPage2" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="400"> <controlsToolkit:BusyIndicator x:Name="busyIndicator" BusyContent="正在加载,请稍等..." IsBusy="True"> <Grid x:Name="LayoutRoot" Background="White"> <esri:Map x:Name="myMap" IsLogoVisible="False" ZoomDuration="0:00:00" PanDuration="0:00:00" Extent="117.647738815324,29.4704217183843,118.446182957997,30.4124245048916"> <esri:ArcGISTiledMapServiceLayer ID="BaseLayer" Url="http://localhost/arcgis/rest/services/HSDQ/MapServer/"/> <!--等值线和等直面图层--> <esri:GraphicsLayer ID="GraphicsDZX"/> </esri:Map> <Grid x:Name="gridMain" HorizontalAlignment="Left" Width="215" Margin="1,0,0,0"> <Grid.ColumnDefinitions> <ColumnDefinition Width="200" x:Name="gridSub2" /> <ColumnDefinition Width="15" x:Name="gridSub1"/> </Grid.ColumnDefinitions> <Grid Grid.Column="1" Background="#FFD2D4D1" Width="15" Margin="-1,0,0,0" d:LayoutOverrides="HorizontalMargin"> <Border BorderBrush="#FFA5C6E5" BorderThickness="2" Width="15"> <Image x:Name="imgExpandOrCollapsed" Margin="0,136,0,117" Source="Images/ss.png" Stretch="Fill" Height="45" MouseLeftButtonDown="imgExpandOrCollapsed_MouseLeftButtonDown" MouseLeftButtonUp="imgExpandOrCollapsed_MouseLeftButtonUp" Cursor="Hand" ToolTipService.ToolTip="收缩/展开"/> </Border> </Grid> <Grid Width="200" HorizontalAlignment="Left" Background="#FFD2D4D1"> <Grid.RowDefinitions> <RowDefinition Height="0.095*"/> <RowDefinition Height="0.905*"/> </Grid.RowDefinitions> <StackPanel Margin="0" Grid.Row="1" VerticalAlignment="Top"> <Grid Height="40" d:LayoutOverrides="Height, VerticalMargin" VerticalAlignment="Top"> <sdk:DatePicker x:Name="dpStart" Margin="38,6,65,6"/> <ComboBox x:Name="cbStart" HorizontalAlignment="Right" Margin="0,6,16,6" Width="49"/> <TextBlock HorizontalAlignment="Left" Margin="3,0,0,0" TextWrapping="Wrap" Text="起始:" Width="40" FontSize="13.333" FontFamily="Microsoft YaHei" VerticalAlignment="Center"/> <TextBlock TextWrapping="Wrap" Text="时" FontSize="13.333" FontFamily="Microsoft YaHei" VerticalAlignment="Center" HorizontalAlignment="Right" Width="15" Margin="0,0,1,0"/> </Grid> <Grid Height="40" d:LayoutOverrides="Height, VerticalMargin"> <sdk:DatePicker x:Name="dpEnd" Margin="38,6,65,6"/> <ComboBox x:Name="cbEnd" HorizontalAlignment="Right" Margin="0,6,16,6" Width="49"/> <TextBlock HorizontalAlignment="Left" Margin="3,0,0,0" TextWrapping="Wrap" Text="截至:" Width="40" FontSize="13.333" FontFamily="Microsoft YaHei" VerticalAlignment="Center"/> <TextBlock TextWrapping="Wrap" Text="时" FontSize="13.333" FontFamily="Microsoft YaHei" VerticalAlignment="Center" HorizontalAlignment="Right" Width="15" Margin="0,0,1,0"/> </Grid> <Grid Height="40" d:LayoutOverrides="Height, VerticalMargin"> <ComboBox x:Name="cbRainGrade" Margin="68,6,0,6"/> <TextBlock HorizontalAlignment="Left" Margin="4,0,0,0" TextWrapping="Wrap" Text="雨量级别:" Width="69" FontSize="13.333" FontFamily="Microsoft YaHei" VerticalAlignment="Center"/> </Grid> <Grid Height="40" d:LayoutOverrides="Height, VerticalMargin"> <RadioButton x:Name="rb1" Content="稀" Margin="70,11,67,1" FontSize="13.333" FontFamily="Microsoft YaHei" GroupName="rbGroup" IsChecked="True" Cursor="Hand" Click="rb_Click"/> <TextBlock HorizontalAlignment="Left" Margin="4,0,0,0" TextWrapping="Wrap" Text="过滤级:" Width="55" FontSize="13.333" FontFamily="Microsoft YaHei" VerticalAlignment="Center"/> <RadioButton x:Name="rb2" Content="密" Margin="0,12,8,0" FontSize="13.333" FontFamily="Microsoft YaHei" HorizontalAlignment="Right" Width="55" GroupName="rbGroup" Cursor="Hand" Click="rb_Click"/> </Grid> <Grid Height="40" d:LayoutOverrides="Height, VerticalMargin"> <Button x:Name="btnAnalysis" Content="等值线分析" Margin="64,0,63,0" VerticalAlignment="Center" Cursor="Hand" FontSize="13.333" FontFamily="Microsoft YaHei" d:LayoutOverrides="Width" Click="btnAnalysis_Click"/> </Grid> </StackPanel> <Border BorderBrush="#FF459BFB" BorderThickness="2" Background="#FF449DFF" Height="30" VerticalAlignment="Top"> <TextBlock HorizontalAlignment="Center" Margin="0" TextWrapping="Wrap" Text="专 题 分 析" Width="82" FontSize="16" FontFamily="Microsoft YaHei" VerticalAlignment="Center" Foreground="White"/> </Border> </Grid> </Grid> </Grid> </controlsToolkit:BusyIndicator> </UserControl> using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes;using ESRI.ArcGIS.Client; using ESRI.ArcGIS.Client.Geometry; using ESRI.ArcGIS.Client.Tasks; using System.Net.Browser; using ESRI.ArcGIS.Client.Symbols; using TestDZX.ServiceReference1; using System.Collections.ObjectModel; using System.Collections; using System.Windows.Media.Imaging; using System.Threading; using System.Globalization; using Syit.CommonClass;namespace TestDZX { public partial class MainPage2 : UserControl { /******************GP参数* 2012-08-29***********************/ private Geoprocessor _ContourTask; //等值线GP public struct EvaluationPointStruct { public double Latitute; //纬度 public double Longitute; //经度 public double YL; //雨量 }; public EvaluationPointStruct[] evaluatePoints; private FeatureSet featureSet;//作为GP输入参数的要素集 ESRI.ArcGIS.Client.Projection.WebMercator mercator = new ESRI.ArcGIS.Client.Projection.WebMercator(); public int Contour_interval = 5; //默认是5表示稀,1表示密 /*********************************************************/ public MainPage2() { InitializeComponent(); //设置日期格式 Thread.CurrentThread.CurrentCulture = (CultureInfo)Thread.CurrentThread.CurrentCulture.Clone(); Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd"; //加载日期 this.dpStart.SelectedDate = (DateTime?)DateTime.Parse(DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd")); this.dpEnd.SelectedDate = (DateTime?)DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd")); //加载小时及雨量级别 BindElement(); //初次加载前日八时到现在小时的数据 DrawContourUseGP(); } #region 页面上数据绑定 public void BindElement() { //起始小时绑定 this.cbStart.Items.Add("00"); this.cbStart.Items.Add("01"); this.cbStart.Items.Add("02"); this.cbStart.Items.Add("03"); this.cbStart.Items.Add("04"); this.cbStart.Items.Add("05"); this.cbStart.Items.Add("06"); this.cbStart.Items.Add("07"); this.cbStart.Items.Add("08"); this.cbStart.Items.Add("09"); this.cbStart.Items.Add("10"); this.cbStart.Items.Add("11"); this.cbStart.Items.Add("12"); this.cbStart.Items.Add("13"); this.cbStart.Items.Add("14"); this.cbStart.Items.Add("15"); this.cbStart.Items.Add("16"); this.cbStart.Items.Add("17"); this.cbStart.Items.Add("18"); this.cbStart.Items.Add("19"); this.cbStart.Items.Add("20"); this.cbStart.Items.Add("21"); this.cbStart.Items.Add("22"); this.cbStart.Items.Add("23"); this.cbStart.SelectedIndex = 8; //结束时间绑定 this.cbEnd.Items.Add("00"); this.cbEnd.Items.Add("01"); this.cbEnd.Items.Add("02"); this.cbEnd.Items.Add("03"); this.cbEnd.Items.Add("04"); this.cbEnd.Items.Add("05"); this.cbEnd.Items.Add("06"); this.cbEnd.Items.Add("07"); this.cbEnd.Items.Add("08"); this.cbEnd.Items.Add("09"); this.cbEnd.Items.Add("10"); this.cbEnd.Items.Add("11"); this.cbEnd.Items.Add("12"); this.cbEnd.Items.Add("13"); this.cbEnd.Items.Add("14"); this.cbEnd.Items.Add("15"); this.cbEnd.Items.Add("16"); this.cbEnd.Items.Add("17"); this.cbEnd.Items.Add("18"); this.cbEnd.Items.Add("19"); this.cbEnd.Items.Add("20"); this.cbEnd.Items.Add("21"); this.cbEnd.Items.Add("22"); this.cbEnd.Items.Add("23"); DateTime dt = DateTime.Now; string hour = dt.Hour.ToString(); if (hour.Length == 1) { hour = "0" + hour; } switch (hour) { case "00": this.cbEnd.SelectedIndex = 0; break; case "01": this.cbEnd.SelectedIndex = 1; break; case "02": this.cbEnd.SelectedIndex = 2; break; case "03": this.cbEnd.SelectedIndex = 3; break; case "04": this.cbEnd.SelectedIndex = 4; break; case "05": this.cbEnd.SelectedIndex = 5; break; case "06": this.cbEnd.SelectedIndex = 6; break; case "07": this.cbEnd.SelectedIndex = 7; break; case "08": this.cbEnd.SelectedIndex = 8; break; case "09": this.cbEnd.SelectedIndex = 9; break; case "10": this.cbEnd.SelectedIndex = 10; break; case "11": this.cbEnd.SelectedIndex = 11; break; case "12": this.cbEnd.SelectedIndex = 12; break; case "13": this.cbEnd.SelectedIndex = 13; break; case "14": this.cbEnd.SelectedIndex = 14; break; case "15": this.cbEnd.SelectedIndex = 15; break; case "16": this.cbEnd.SelectedIndex = 16; break; case "17": this.cbEnd.SelectedIndex = 17; break; case "18": this.cbEnd.SelectedIndex = 18; break; case "19": this.cbEnd.SelectedIndex = 19; break; case "20": this.cbEnd.SelectedIndex = 20; break; case "21": this.cbEnd.SelectedIndex = 21; break; case "22": this.cbEnd.SelectedIndex = 22; break; case "23": this.cbEnd.SelectedIndex = 23; break; } //绑定雨量级别 this.cbRainGrade.Items.Add("A:5,10,25,50,100,200"); this.cbRainGrade.Items.Add("B:10,25,50,100,200,300"); this.cbRainGrade.Items.Add("C:50,100,200,300,400,500,600"); this.cbRainGrade.Items.Add("D:100,200,300,400,600,700"); this.cbRainGrade.Items.Add("E:10,20,30,40,50,60"); this.cbRainGrade.SelectedIndex = 0; } #endregion #region 调用GP服务绘制等值线 /// <summary> /// 调用GP服务绘制等值线 /// </summary> public void DrawContourUseGP() { Thread.Sleep(1000); //加载之前,显示等待 busyIndicator.IsBusy = true; try { getXQYJInfoSoapClient client = new getXQYJInfoSoapClient(); //水位数据 client.getSWRainByTimeSpanCompleted += new EventHandler<getSWRainByTimeSpanCompletedEventArgs>(client_getSWRainByTimeSpanCompleted); client.getSWRainByTimeSpanAsync(DateTime.Parse(this.dpStart.SelectedDate.ToString().Split(' ')[0] + " " + this.cbStart.SelectedItem.ToString() + ":00:00"), DateTime.Parse(this.dpEnd.SelectedDate.ToString().Split(' ')[0] + " " + this.cbEnd.SelectedItem.ToString() + ":00:00")); } catch (Exception) { } } void client_getSWRainByTimeSpanCompleted(object sender, getSWRainByTimeSpanCompletedEventArgs e) { try { //获取到所有的水文局雨量点 ObservableCollection<RainFall> lists = e.Result; int PointsNum = lists.Count;//点的个数 evaluatePoints = new EvaluationPointStruct[PointsNum]; int index = 0; foreach (RainFall item in lists) { if (item.YL24 != 0) { evaluatePoints[index].Latitute = item.Latitute; evaluatePoints[index].Longitute = item.Longitute; evaluatePoints[index].YL = item.YL24; index++; } } Utility.AddPointToMapLayer(myMap, evaluatePoints, out featureSet); AccessGPService(featureSet); } catch (Exception) { } } private void AccessGPService(FeatureSet featureset) { try { HttpWebRequest.RegisterPrefix("http://", System.Net.Browser.WebRequestCreator.ClientHttp); _ContourTask = new Geoprocessor("http://localhost/arcgis/rest/services/ContourServiceTool/GPServer/Contour"); List<GPParameter> parameters = new List<GPParameter>(); parameters.Add(new GPFeatureRecordSetLayer("Input_point_features", featureset)); parameters.Add(new GPDouble("Contour_interval", Contour_interval)); _ContourTask.UpdateDelay = 5000; // 10s的更新时间 _ContourTask.OutputSpatialReference = myMap.SpatialReference; //设置输出空间参考系 _ContourTask.JobCompleted += new EventHandler<JobInfoEventArgs>(geoprocessorTask_JobCompleted); _ContourTask.Failed += new EventHandler<TaskFailedEventArgs>(geoprocessorTask_Failed); _ContourTask.SubmitJobAsync(parameters); } catch (Exception) { } } /********************************事件处理程序段***************************************/ void geoprocessorTask_JobCompleted(object sender, JobInfoEventArgs e) { Geoprocessor gp = sender as Geoprocessor; //注册前缀 HttpWebRequest.RegisterPrefix("http://", System.Net.Browser.WebRequestCreator.ClientHttp); gp.GetResultDataCompleted += new EventHandler<GPParameterEventArgs>(gp_GetResultDataCompleted); gp.GetResultDataAsync(e.JobInfo.JobId, "Contour_Idw_11_Clip_SmoothLi_shp"); //加载完成,隐藏 busyIndicator.IsBusy = false; } void gp_GetResultDataCompleted(object sender, GPParameterEventArgs e) { //找到显示等值线图层并清空,然后再次加载 GraphicsLayer layer = myMap.Layers["GraphicsDZX"] as GraphicsLayer; layer.ClearGraphics(); GPFeatureRecordSetLayer gplayer = e.Parameter as GPFeatureRecordSetLayer; int index = 0; foreach (Graphic graphic in gplayer.FeatureSet.Features) { if (IsRainInGrade(graphic.Attributes["CONTOUR"].ToString())) { graphic.Symbol = new ESRI.ArcGIS.Client.Symbols.SimpleLineSymbol() { Style = ESRI.ArcGIS.Client.Symbols.SimpleLineSymbol.LineStyle.Solid, Color = new SolidColorBrush(Colors.Red), Width = 2 }; layer.Graphics.Add(graphic); //添加红色的等值线 /****************************************************************************************/ //标注数值 TextSymbol textSymbol = new TextSymbol() { FontFamily = new System.Windows.Media.FontFamily("Microsoft YaHei"), Foreground = new System.Windows.Media.SolidColorBrush(Color.FromArgb(255, 0, 0, 0)), FontSize = 12, Text = graphic.Attributes["CONTOUR"].ToString() }; //寻找线段的中心点坐标位置 Graphic graphicText; //封闭曲线在曲线中间显示数值 Graphic graphicStart; //非封闭曲线的起始点 Graphic graphicEnd; //非封闭曲线的终止点 if (gplayer.FeatureSet.GeometryType == GeometryType.Polyline) { ESRI.ArcGIS.Client.Geometry.Polyline pl = gplayer.FeatureSet.Features[index].Geometry as ESRI.ArcGIS.Client.Geometry.Polyline; MapPoint mp = pl.Extent.GetCenter(); if (pl.Paths != null && pl.Paths.Count > 0) { ESRI.ArcGIS.Client.Geometry.PointCollection path = pl.Paths[0]; if (path != null && path.Count > 0) { int mid = path.Count / 2; mp = path[mid]; if (path.Count == 2) { // path里面只有两个点的情况 double x1 = (path[0] as MapPoint).X; double y1 = (path[0] as MapPoint).Y; double x2 = (path[1] as MapPoint).X; double y2 = (path[1] as MapPoint).Y; mp.X = x2 + (x1 - x2) / 2; mp.Y = y2 + (y1 - y2) / 2; //封闭的曲线 graphicText = new Graphic() { Geometry = mercator.FromGeographic(mp), Symbol = textSymbol }; //封闭的曲线在中间位置 layer.Graphics.Add(graphicText); //添加数值 } else { //起始 graphicStart = new Graphic() { Geometry = mercator.FromGeographic(new MapPoint(path[0].X, path[0].Y)), Symbol = textSymbol }; //结束 graphicEnd = new Graphic() { Geometry = mercator.FromGeographic(new MapPoint(path[path.Count - 1].X, path[path.Count - 1].Y)), Symbol = textSymbol }; layer.Graphics.Add(graphicStart); //标注起始数值 layer.Graphics.Add(graphicEnd); //标注结束数值 } } } } } //索引自增字段 index++; } } /// <summary> /// 地理处理失败,返回失败原因 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void geoprocessorTask_Failed(object sender, TaskFailedEventArgs e) { MessageBox.Show(e.Error.ToString()); } /// <summary> /// 等值线分析按钮 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnAnalysis_Click(object sender, RoutedEventArgs e) { DrawContourUseGP(); } #endregion #region 菜单处理选项及事件 private void imgExpandOrCollapsed_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e) { e.Handled = true; } private void imgExpandOrCollapsed_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e) { if (this.gridSub2.Width == new GridLength(200, GridUnitType.Pixel)) { //处于展开状态 this.imgExpandOrCollapsed.Tag = "收缩面板"; Grid.SetColumnSpan(gridMain, 1); this.gridSub2.Width = new GridLength(0, GridUnitType.Pixel); Uri uri = new Uri("Images/zk.png", UriKind.Relative); BitmapImage image = new BitmapImage(uri); this.imgExpandOrCollapsed.Source = image; } else { //处于收缩状态 this.imgExpandOrCollapsed.Tag = "展开面板"; Grid.SetColumnSpan(gridMain, 2); this.gridSub2.Width = new GridLength(200, GridUnitType.Pixel); Uri uri = new Uri("Images/ss.png", UriKind.Relative); BitmapImage image = new BitmapImage(uri); this.imgExpandOrCollapsed.Source = image; } } /// <summary> /// 过滤级单选按钮的切换事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void rb_Click(object sender, RoutedEventArgs e) { RadioButton currRadioButton; currRadioButton = sender as RadioButton; if (currRadioButton != null && currRadioButton.IsChecked.Value) { if (currRadioButton.Name == "rb1") { //首先赋值Contour_interval Contour_interval = 5; //改变值后,重新加载等值线 DrawContourUseGP(); } else if (currRadioButton.Name == "rb2") { //首先赋值Contour_interval Contour_interval = 1; //改变值后,重新加载等值线 DrawContourUseGP(); } } } #endregion #region 根据雨量等级进行数据筛选 /// <summary> /// 判断一个降雨值取整数后,是否在雨量级别的数值中 /// </summary> /// <param name="value"></param> /// <returns>在数值中的话,返回true,否则返回false</returns> public bool IsRainInGrade(string value) { bool flag = false; string[] list = this.cbRainGrade.SelectedItem.ToString().Trim().Split(':')[1].Split(','); foreach (string s in list) { if (value.Trim() == s) { flag = true; } } return flag; } #endregion } } 使用到的另一个cs类文件如下Utility.cs文件如下 using System; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using ESRI.ArcGIS.Client.Geometry; using ESRI.ArcGIS.Client; using ESRI.ArcGIS.Client.Tasks; using ESRI.ArcGIS.Client.Symbols;namespace TestDZX { public class Utility { public static void AddPointToMapLayer(ESRI.ArcGIS.Client.Map map, MainPage2.EvaluationPointStruct[] evaluatePoints, out ESRI.ArcGIS.Client.Tasks.FeatureSet featureset) { ESRI.ArcGIS.Client.Projection.WebMercator mercator = new ESRI.ArcGIS.Client.Projection.WebMercator(); #region 动态添加预测点图层 if (map.Layers["YLPointsLayer"] != null) { map.Layers.Remove(map.Layers["YLPointsLayer"]); } GraphicsLayer graphicslayer = new GraphicsLayer() { ID = "YLPointsLayer", }; map.Layers.Add(graphicslayer); #endregion #region 将降雨量点添加到图层中 featureset = new FeatureSet(); if (evaluatePoints.Length != 0) { foreach (MainPage2.EvaluationPointStruct evaluationpoint in evaluatePoints) { Graphic g = new Graphic() { Geometry = mercator.FromGeographic(new MapPoint(evaluationpoint.Latitute, evaluationpoint.Longitute)), Symbol = new ESRI.ArcGIS.Client.Symbols.SimpleMarkerSymbol() { Style = ESRI.ArcGIS.Client.Symbols.SimpleMarkerSymbol.SimpleMarkerStyle.Circle, Size = 5, Color = new SolidColorBrush(Colors.Red) } }; g.Attributes.Add("YL", evaluationpoint.YL); featureset.Features.Add(g); graphicslayer.Graphics.Add(g); //动态添加文本 TextSymbol textSymbol = new TextSymbol() { FontFamily = new System.Windows.Media.FontFamily("Microsoft YaHei"), Foreground = new System.Windows.Media.SolidColorBrush(Color.FromArgb(255, 117, 20, 99)), FontSize = 12, Text = evaluationpoint.YL.ToString(), OffsetX = 12, OffsetY = -5 }; Graphic graphicText = new Graphic() { Geometry = mercator.FromGeographic(new MapPoint(evaluationpoint.Latitute, evaluationpoint.Longitute)), Symbol = textSymbol }; graphicslayer.Graphics.Add(graphicText); } } #endregion } } }
显示效果如下:
===========================================================================
如果觉得对您有帮助,微信扫一扫支持一下: