arcgis server for .NET学习转载4

http://www.cnblogs.com/hll2008/archive/2008/08/17/1269650.html
目的:
1.距离测量功能
准备:
1.(一、三)的工程,具体见前篇。

开始:
1.新建名为Measure.ascx的用户控件,并且实现ICallbackEventHandler接口,具体代码如下:
 1namespace MappingApp
 2{
 3    public partial class Measure : System.Web.UI.UserControl, ICallbackEventHandler
 4    {
 5        protected void Page_Load(object sender, EventArgs e)
 6        {
 7
 8        }

 9
10        #region ICallbackEventHandler 成员
11
12        //负责把结果回传给客户端
13        public string GetCallbackResult()
14        {
15            throw new Exception("The method or operation is not implemented.");
16        }

17
18        //负责从客户端javascript传来的参数
19        public void RaiseCallbackEvent(string eventArgument)
20        {
21            throw new Exception("The method or operation is not implemented.");
22        }

23
24        #endregion

25    }

26}
2. 加入具体的线距离测量和面积测量功能代码,具体的代码和说明如下:
  1namespace MappingApp
  2{
  3    //地图单位
  4    public enum MapUnit
  5    {
  6        Resource_Default, Degrees, Feet, Meters //默认,度,码,米
  7    }

  8
  9    //测量单位
 10    public enum MeasureUnit
 11    {
 12        Feet, Kilometers, Meters, Miles //码,千米,米,英里
 13    }

 14
 15    //区域单位
 16    public enum AreaUnit
 17    {
 18        Acres, Sq_Feet, Sq_Kilometers, Sq_Meters, Sq_Miles //英亩,平方码,平方千米,平方米,平方英里
 19    }

 20
 21    public partial class Measure : System.Web.UI.UserControl, ICallbackEventHandler
 22    {
 23        MapResourceManager m_resourceManger;
 24        IMapFunctionality m_mapFunctionality;
 25        //页面
 26        private Page m_page;
 27        //客户端代码段
 28        public string m_callbackInvocation = "";
 29        //地图控件ID
 30        private string m_mapBuddyId = "Map1";
 31        //用户控件id
 32        public string m_id;
 33        //地图控件
 34        private Map m_map;
 35        //默认地图单位
 36        private MapUnit m_FallbackMapUnit = MapUnit.Degrees; 
 37        private MapUnit m_mapUnits;
 38        //
 39        private MapUnit m_startMapUnits = MapUnit.Degrees;
 40        //默认测量单位
 41        public MeasureUnit m_measureUnits = MeasureUnit.Miles;
 42        //默认区域单位
 43        public AreaUnit m_areaUnits = AreaUnit.Sq_Miles;
 44        //数字精确到4位
 45        private double m_numberDecimals = 4;
 46
 47        protected void Page_Load(object sender, EventArgs e)
 48        {
 49            //控件id
 50            m_id = this.ClientID;
 51            //页面
 52            m_page = this.Page;
 53            if (m_mapBuddyId == null || m_mapBuddyId.Length == 0)
 54            {
 55                m_mapBuddyId = "Map1";
 56            }

 57            //获取map控件
 58            m_map = m_page.FindControl(m_mapBuddyId) as Map;
 59            //获取MapResourceManager控件
 60            m_resourceManger = m_page.FindControl(m_map.MapResourceManager) as MapResourceManager;
 61            //通过GetCallbackEventReference生成客户端调用的javascript方法段
 62            m_callbackInvocation = m_page.ClientScript.GetCallbackEventReference(this"argument""processCallbackResult""context"true);
 63        }

 64
 65        //
 66        protected void Page_PreRender(object sender, EventArgs e)
 67        {
 68            GetMeasureResource();
 69        }

 70
 71        private void GetMeasureResource()
 72        {
 73            string primeResource = m_map.PrimaryMapResource;
 74            IEnumerable mapResources = m_resourceManger.GetResources();
 75            IEnumerator resEnum = mapResources.GetEnumerator();
 76           
 77            resEnum.MoveNext();
 78
 79            IGISResource resource;
 80            if (primeResource != null && primeResource.Length > 0)
 81            {
 82                resource = m_resourceManger.GetResource(primeResource);
 83            }

 84            else
 85            {
 86                resource = resEnum.Current as IGISResource;
 87            }

 88
 89            if (resource != null)
 90            {
 91                m_mapFunctionality = (IMapFunctionality)resource.CreateFunctionality(typeof(IMapFunctionality), "mapFunctionality");
 92            }

 93        }

 94
 95        ICallbackEventHandler 成员
163
164        //根据请求字符串进行不同的测量
165        public string ProcessMeasureRequest(NameValueCollection queryString)
166        {
167            if (m_mapFunctionality == null)
168            {
169                GetMeasureResource();
170            }

171            object o = Session["MeasureMapUnits"];
172            if (o != null)
173            {
174                m_mapUnits = (MapUnit)Enum.Parse(typeof(MapUnit), o.ToString());
175            }

176            else if (m_startMapUnits == MapUnit.Resource_Default)
177            {
178                //获取默认地图单位
179                m_mapUnits = GetResourceDefaultMapUnit();
180            }

181            else
182            {
183                m_mapUnits = m_startMapUnits;
184            }

185
186            //请求参数
187            string eventArg = queryString["EventArg"].ToLower();
188            string vectorAction = queryString["VectorAction"].ToLower();
189            string[] coordPairs, xys;
190            //坐标字符串
191            string coordString = queryString["coords"];
192            if (coordString == null && coordString.Length == 0)
193            {
194                coordString = "";
195            }

196            //坐标字符串分割
197            coordPairs = coordString.Split(char.Parse("|"));
198            //地图单位
199            string mapUnitString = queryString["MapUnits"];
200            if (mapUnitString != null && mapUnitString.Length > 0)
201            {
202                m_mapUnits = (MapUnit)Enum.Parse(typeof(MapUnit), mapUnitString);
203            }

204            Session["MeasureMapUnits"= m_mapUnits;
205            //测量单位
206            string measureUnitString = queryString["MeasureUnits"];
207            if (measureUnitString != null && measureUnitString.Length > 0)
208            {
209                m_measureUnits = (MeasureUnit)Enum.Parse(typeof(MeasureUnit), measureUnitString);
210            }

211            //区域单位
212            string areaUnitstring = queryString["AreaUnits"];
213            if (areaUnitstring != null && areaUnitstring.Length > 0)
214            {
215                m_areaUnits = (AreaUnit)Enum.Parse(typeof(AreaUnit), areaUnitstring);
216            }

217
218            //输出内容字符串
219            string response = "";
220            PointCollection points = new PointCollection();
221            PointCollection dPoints = new PointCollection();
222            ArrayList distances = new ArrayList();
223            double totalDistance = 0;
224            double segmentDistance = 0;
225            double area = 0;
226            double perimeter = 0;
227            double roundFactor = Math.Pow(10, m_numberDecimals);
228            double xD, yD, tempDist, tempDist2, tempArea, x1, x2, y1, y2;
229
230            //动作为添加点
231            if (vectorAction == "addpoint")
232            {
233                //坐标点大于1个时,就是保证是一条线
234                if (coordPairs != null && coordPairs.Length > 1)
235                {
236                    for (int i = 0; i < coordPairs.Length; i++)
237                    {
238                        xys = coordPairs[i].Split(char.Parse(":"));
239                        //像素坐标转换成地理坐标
240                        points.Add(Point.ToMapPoint(Convert.ToInt32(xys[0]), Convert.ToInt32(xys[1]), m_map.GetTransformationParams(ESRI.ArcGIS.ADF.Web.Geometry.TransformationDirection.ToMap)));
241
242                        if (i > 0)//第二个坐标点的时候
243                        {
244                            if (m_mapUnits == MapUnit.Degrees)//地图单位为度的时候
245                            {
246                                //计算与前一个点的距离,分段距离
247                                tempDist = DegreeToFeetDistance(points[i - 1].X, points[i - 1].Y, points[i].X, points[i].Y);
248                                //度转成码
249                                y1 = DegreeToFeetDistance(points[i].X, points[i].Y, points[i].X, 0);
250                                //度转成码
251                                x1 = DegreeToFeetDistance(points[i].X, points[i].Y, 0, points[i].Y);
252                                dPoints.Add(new Point(x1, y1));
253                                //单位换算
254                                segmentDistance = ConvertUnits(tempDist, MapUnit.Feet, m_measureUnits);
255                            }

256                            else//地图单位为米的时候
257                            {
258                                xD = Math.Abs(points[i].X - points[i - 1].X);
259                                yD = Math.Abs(points[i].Y - points[i - 1].Y);
260                                //计算2个坐标之间的距离
261                                tempDist = Math.Sqrt(Math.Pow(xD, 2+ Math.Pow(yD, 2));
262                                //单位换算
263                                segmentDistance = ConvertUnits(tempDist, m_mapUnits, m_measureUnits);
264
265                            }

266
267                            //把分段距离添加到distances
268                            distances.Add(segmentDistance);
269                            //计算总距离
270                            totalDistance += segmentDistance;
271                            //只显示4位小数
272                            segmentDistance = Math.Round(segmentDistance * roundFactor) / roundFactor;
273                            totalDistance = Math.Round(totalDistance * roundFactor) / roundFactor;
274                        }

275                        else//第一个坐标点的时候
276                        {
277                            if (m_mapUnits == MapUnit.Degrees)
278                            {
279                                //度转成码
280                                y1 = DegreeToFeetDistance(points[i].X, points[i].Y, points[i].X, 0);
281                                x1 = DegreeToFeetDistance(points[i].X, points[i].Y, 0, points[i].Y);
282                                dPoints.Add(new Point(x1, y1));
283                            }

284                        }

285                    }

286                }

287
288                //为多边形时
289                if (eventArg == "polygon")
290                {
291                    if (points.Count > 2)
292                    {
293                        if (m_mapUnits == MapUnit.Degrees)
294                        {
295                            //最后一段的距离计算
296                            tempDist = DegreeToFeetDistance(points[points.Count - 1].X, points[points.Count - 1].Y, points[0].X, points[0].Y);
297                            tempDist2 = ConvertUnits(tempDist, MapUnit.Feet, m_measureUnits);
298                            distances.Add(tempDist2);
299                            //加入第一点作为多边形的结束节点
300                            dPoints.Add(dPoints[0]);
301                        }

302                        else
303                        {
304                            //最后一段的距离计算
305                            xD = Math.Abs(points[points.Count - 1].X - points[0].X);
306                            yD = Math.Abs(points[points.Count - 1].Y - points[0].Y);
307                            tempDist = Math.Sqrt(Math.Pow(xD, 2+ Math.Pow(yD, 2));
308                            tempDist2 = ConvertUnits(tempDist, m_mapUnits, m_measureUnits);
309                            distances.Add(tempDist2);
310                        }

311                        //加入第一点作为多边形的结束节点
312                        points.Add(points[0]);
313                        //总长度+最后一段长度
314                        perimeter = totalDistance + tempDist2;
315                        //多边形面积计算
316                        tempArea = 0;
317                        MapUnit mUnits = m_mapUnits;
318                        for (int j = 0; j < points.Count - 1; j++)
319                        {
320                            if (m_mapUnits == MapUnit.Degrees)
321                            {
322                                x1 = Convert.ToDouble(dPoints[j].X);
323                                x2 = Convert.ToDouble(dPoints[j + 1].X);
324                                y1 = Convert.ToDouble(dPoints[j].Y);
325                                y2 = Convert.ToDouble(dPoints[j + 1].Y);
326                                mUnits = MapUnit.Feet;
327                            }

328                            else
329                            {
330                                x1 = Convert.ToDouble(points[j].X);
331                                x2 = Convert.ToDouble(points[j + 1].X);
332                                y1 = Convert.ToDouble(points[j].Y);
333                                y2 = Convert.ToDouble(points[j + 1].Y);
334                            }

335                            //tempArea += tempArea + (x1 + x2) * (y1 - y2);
336                            double xDiff = x2 - x1;
337                            double yDiff = y2 - y1;
338                            tempArea += x1 * yDiff - y1 * xDiff;
339                        }

340                        tempArea = Math.Abs(tempArea) / 2;
341                        //单位换算
342                        area = ConvertAreaUnits(tempArea, mUnits, m_areaUnits);
343                        //保留4位小数
344                        perimeter = Math.Round(perimeter * roundFactor) / roundFactor;
345                        area = Math.Round(area * roundFactor) / roundFactor;
346
347                        //输出显示内容html
348                        response = String.Format("<table cellspacing='0'  ><tr><td>Perimeter: </td><td align='right'>{0}</td><td>{1}</td></tr><tr><td>Area:</td><td  align='right'>{2}</td><td>{3}</td></tr></table>", perimeter, WriteMeasureUnitDropdown(), area, WriteAreaUnitDropdown());
349                    }

350                    else
351                    {
352                        //输出显示内容html,小于3个点时候
353                        response = String.Format("<table cellspacing='0' ><tr><td>Perimeter: </td><td align='right'> 0</td><td>{0}</td></tr><tr><td>Area:</td><td align='right'>0 </td><td>{1}</td></tr></table>", WriteMeasureUnitDropdown(), WriteAreaUnitDropdown());
354                    }

355                }

356                else
357                {
358                    //输出显示内容html,为线的时候
359                    response = String.Format("<table cellspacing='0' ><tr><td>Segment: </td><td align='right'>{0} </td><td>{1}</td></tr><tr><td>Total Length:</td><td align='right'>{2} </td><td>{3}</td></tr></table>", segmentDistance, m_measureUnits.ToString(), totalDistance, WriteMeasureUnitDropdown());
360                }

361
362            }

363            //动作为获取坐标
364            else if (vectorAction == "coordinates")
365            {
366                xys = coordPairs[0].Split(char.Parse(":"));
367                Point coordPoint = Point.ToMapPoint(Convert.ToInt32(xys[0]), Convert.ToInt32(xys[1]), m_map.GetTransformationParams(ESRI.ArcGIS.ADF.Web.Geometry.TransformationDirection.ToMap));
368
369                //输出坐标的html显示内容
370                response = String.Format("<table cellspacing='0' ><tr><td>X Coordinate:</td><td align='right'>{0}</td></tr><tr><td>Y Coordinate:</td><td align='right'>{1}</td></tr></table>", (Math.Round(coordPoint.X * roundFactor) / roundFactor).ToString(), (Math.Round(coordPoint.Y * roundFactor) / roundFactor).ToString());
371            }

372            //动作为结束画线
373            else if (vectorAction == "finish")
374            {
375                response = "Shape complete";
376            }

377
378            //把结果内容返回给客户端
379            return String.Format("measure:::{0}:::{1}:::{2}", m_id, vectorAction, response);
380        }

381
382        //输出测量单位选择下拉框
383        public string WriteMeasureUnitDropdown()
384        {
385            System.Text.StringBuilder sb = new System.Text.StringBuilder();
386            sb.Append("<select id=\"MeasureUnits2\" onchange=\"changeMeasureUnits()\" style=\"font: normal 7pt Verdana; width: 100px;\">");
387            Array mArray = Enum.GetValues(typeof(MeasureUnit));
388            foreach (MeasureUnit mu in mArray)
389            {
390                sb.AppendFormat("<option value=\"{0}\" {1}>{0}</option>", mu.ToString(), CheckFormMeasureUnits(mu.ToString()));
391
392            }

393            sb.Append("</select>");
394
395            return sb.ToString();
396        }

397
398        //检查默认选中项
399        public string CheckFormMeasureUnits(string unit)
400        {
401            string response = "";
402            if (unit == m_measureUnits.ToString())
403                response = "selected=\"selected\"";
404            return response;
405        }

406
407        //输出测量单位选择下拉框
408        public string WriteAreaUnitDropdown()
409        {
410            System.Text.StringBuilder sb = new System.Text.StringBuilder();
411            sb.Append("<select id=\"AreaUnits2\" onchange=\"changeAreaUnits()\" style=\"font: normal 7pt Verdana; width: 100px;\">");
412            Array aArray = Enum.GetValues(typeof(AreaUnit));
413            foreach (AreaUnit au in aArray)
414            {
415                sb.AppendFormat("<option value=\"{0}\" {1}>{0}</option>", au.ToString(), CheckFormAreaUnits(au.ToString()));
416
417            }

418            sb.Append("</select>");
419
420            return sb.ToString();
421        }

422
423        //检查默认选中项
424        public string CheckFormAreaUnits(string unit)
425        {
426            string response = "";
427            if (unit == m_areaUnits.ToString())
428                response = "selected=\"selected\"";
429            return response;
430        }

431
432        //面积单位换算
433        private double ConvertAreaUnits(double area, MapUnit baseUnits, AreaUnit toUnits)
434        {
435            double mArea = area;
436            if (baseUnits == MapUnit.Feet)
437            {
438                if (toUnits == AreaUnit.Acres)
439                    mArea = area * 0.000022956;
440                else if (toUnits == AreaUnit.Sq_Meters)
441                    mArea = area * 0.09290304;
442                else if (toUnits == AreaUnit.Sq_Miles)
443                    mArea = area * 0.00000003587;
444                else if (toUnits == AreaUnit.Sq_Kilometers)
445                    mArea = area * 0.09290304 / 1000000;
446            }

447            else if (baseUnits == MapUnit.Meters)
448            {
449                if (toUnits == AreaUnit.Acres)
450                    mArea = area * 0.0002471054;
451                else if (toUnits == AreaUnit.Sq_Miles)
452                    mArea = area * 0.0000003861003;
453                else if (toUnits == AreaUnit.Sq_Kilometers)
454                    mArea = area * 1.0e-6;
455                else if (toUnits == AreaUnit.Sq_Feet)
456                    mArea = area * 10.76391042;
457            }

458
459            return mArea;
460        }

461
462        //单位换算
463        public double ConvertUnits(double distance, MapUnit fromUnits, MeasureUnit toUnits)
464        {
465            double mDistance = distance;
466            if (fromUnits == MapUnit.Feet)
467            {
468                if (toUnits == MeasureUnit.Miles)
469                {
470                    mDistance = distance / 5280;
471                }

472                else if (toUnits == MeasureUnit.Meters)
473                {
474                    mDistance = distance * 0.304800609601;
475                }

476                else if (toUnits == MeasureUnit.Kilometers)
477                {
478                    mDistance = distance * 0.0003048;
479                }

480            }

481            else
482            {
483                if (toUnits == MeasureUnit.Miles)
484                {
485                    mDistance = distance * 0.0006213700922;
486                }

487                else if (toUnits == MeasureUnit.Feet)
488                {
489                    mDistance = distance * 3.280839895;
490                }

491                else if (toUnits == MeasureUnit.Kilometers)
492                {
493                    mDistance = distance / 1000;
494                }

495            }

496            return mDistance;
497        }

498
499        //度转成码距离
500        private double DegreeToFeetDistance(double x1, double y1, double x2, double y2)
501        {
502            double Lat1 = DegToRad(y1);
503            double Lat2 = DegToRad(y2);
504            double Lon1 = DegToRad(x1);
505            double Lon2 = DegToRad(x2);
506            double LonDist = Lon1 - Lon2;
507            double LatDist = Lat1 - Lat2;
508            double x = Math.Pow(Math.Sin(LatDist / 2), 2+ Math.Cos(Lat1) * Math.Cos(Lat2) * Math.Pow(Math.Sin(LonDist / 2), 2);
509            x = 2 * Math.Asin(Math.Min(1, Math.Sqrt(x)));
510            x = (3963 - 13 * Math.Sin((Lat1 + Lat2) / 2)) * x;
511            // in miles convert to feet and use that as base
512            return (x * 5280);
513        }

514
515        //度转成弧度
516        private double DegToRad(double degrees)
517        {
518            return Convert.ToDouble(degrees * Math.PI / 180);
519        }

520
521        private MapUnit GetResourceDefaultMapUnit()
522        {
523            MapUnit mUnit = MapUnit.Degrees;
524            try
525            {
526                //获取地图资源单位
527                Units mu = m_mapFunctionality.Units;
528                if (mu == Units.DecimalDegrees)
529                {
530                    mUnit = MapUnit.Degrees;
531                }
  
532                else if (mu == Units.Feet)
533                {
534                    mUnit = MapUnit.Feet;
535                }

536                else if (mu == Units.Meters)
537                {
538                    mUnit = MapUnit.Meters;
539                }

540                    
541            }

542            catch
543            {
544                //不能获取地图资源单位时用m_FallbackMapUnit定义的单位
545                mUnit = m_FallbackMapUnit;
546            }

547            return mUnit;
548
549        }

550
551        public string Id
552        {
553            get return m_id; }
554            set { m_id = value; }
555        }

556
557        private string ClientCallbackInvocation
558        {
559            get return m_callbackInvocation; }
560            set { m_callbackInvocation = value; }
561        }

562
563        private MapResourceManager MapResourceManager
564        {
565            get return m_resourceManger; }
566            set { m_resourceManger = value; }
567        }

568
569        /// <summary>
570        /// Id of Buddy MapControl
571        /// </summary>

572        public string MapBuddyId
573        {
574            get return m_mapBuddyId; }
575            set { m_mapBuddyId = value; }
576        }

577
578
579        /// <summary>
580        /// Unit used resource. Resource_Default will return value from resource, if available. Other values will force calculations to use that unit.
581        /// </summary>

582        public MapUnit MapUnits
583        {
584            get return m_startMapUnits; }
585            set { m_startMapUnits = value; }
586        }

587
588        /// <summary>
589        ///  Unit used in display of linear measurements.
590        /// </summary>

591        public MeasureUnit MeasureUnits
592        {
593            get return m_measureUnits; }
594            set { m_measureUnits = value; }
595        }

596
597        /// <summary>
598        ///  Area Units - Unit used in display of area measurements.
599        /// </summary>

600        public AreaUnit AreaUnits
601        {
602            get return m_areaUnits; }
603            set { m_areaUnits = value; }
604        }

605
606        // Number of Decimals - Number of decimal digits displayed in measurements.
607        public double NumberDecimals
608        {
609            get return m_numberDecimals; }
610            set { m_numberDecimals = value; }
611        }

612
613
614        public override bool Visible
615        {
616            get return base.Visible; }
617        }

618
619        public override bool EnableTheming
620        {
621            get
622            {
623                return base.EnableTheming;
624            }

625        }

626
627        public override bool EnableViewState
628        {
629            get
630            {
631                return base.EnableViewState;
632            }

633        }

634
635    }

636}

4.切换到Measure.ascx的html代码视图,给主table添加id为MeasureToolbar,添加style属性为color:Black;background-color:White;border-color:Black; border-width:1px;border-style:Outset;width:275px;visibility:hidden;position: absolute;  left: 285px; top: 298px; z-index:11000; 这样可以是这个用户控件浮在地图之上同时默认为不显示。
5.其他的也做相应的设置,完成后的代码和说明如下:
 1<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Measure.ascx.cs" Inherits="MappingApp.Measure" %>
 2<script language="javascript" type="text/javascript" src="JavaScript/display_measure.js"></script>
 3<style type="text/css">
 4<!--
 5.STYLE1 {
 6    font-size: 12px;
 7    font-weight: bold;
 8}

 9-->
10
</style>
11
12<table width="400" border="1" cellspacing="0" cellpadding="0" id="MeasureToolbar" style="color:Black;background-color:White;border-color:Black; border-width:1px;border-style:Outset;width:275px;visibility:hidden;position: absolute;  left: 10px; top: 10px; z-index:11000; ">
13  <!-- 给tr加上拖拽的事件 -->
14  <tr id="MeasureToolbar_Title" onmousedown="dragMeasureToolbarStart(event, 'MeasureToolbar')" onmouseover="this.style.cursor='move'" style="background-image:url(images/blank.gif); cursor:move; ">
15    <td><table width="100%" border="0" cellspacing="0" cellpadding="0">
16      <tr>
17        <td width="92%"><span class="STYLE1">距离测量</span></td>
18        <td width="30">
19        <!-- 给给关闭按钮图片加上关闭事件的事件 -->
20        <img src="images/dismiss.png" width="20" height="20" id="MeasureToolbar_CloseButton" onclick="closeMeasureToolbarTool('MeasureToolbar')" style="cursor:pointer;" alt="Close" hspace="0" vspace="0" /></td>
21      </tr>
22      <tr>
23        <td><table cellpadding="0" cellspacing="0" ><tr>
24                        <!-- 点功能按钮 -->
25                        <td id="MeasureToolbarButton_point" style="border: solid White 1px; background-color: White;" onmouseover="this.style.cursor='pointer'; this.style.borderColor='Black';" onmouseout="checkMeasureToolbarBorder(this, 'point')" onmousedown="setMeasureToolbarTool('point')"><img id="ToolbarImage_point" src="images/measure-point.png" align="middle" alt="Point - Coordinates" title="Point - Coordinates" style="padding: 0px 0px 0px 0px" /></td>
26                        <!-- 线功能按钮 -->
27                        <td id="MeasureToolbarButton_polyline" style="border: solid Black 1px; background-color: #EEEEEE;" onmouseover="this.style.cursor='pointer';this.style.borderColor='Black';" onmouseout="checkMeasureToolbarBorder(this, 'polyline')" onmousedown="setMeasureToolbarTool('polyline')"><img id="ToolbarImage_polyline" src="images/measure-line.png" align="middle" alt="Line - Distance" title="Line - Distance" style="padding: 0px 0px 0px 0px" /></td>
28                        <!-- 面功能按钮 -->
29                        <td id="MeasureToolbarButton_polygon" style="border: solid White 1px; background-color: White;" onmouseover="this.style.cursor='pointer';this.style.borderColor='Black';" onmouseout="checkMeasureToolbarBorder(this, 'polygon')" onmousedown="setMeasureToolbarTool('polygon')"><img id="ToolbarImage_polygon" src="images/measure-poly.png" align="middle" alt="Polygon - Area" title="Polygon - Area" style="padding: 0px 0px 0px 0px" />    </td>
30                        </tr></table>
31                        <!-- 测试单位隐藏值 -->
32                        <input id="MeasureUnits" type="hidden" value="<%=MeasureUnits %>"/>
33                        <!-- 面积单位隐藏值 -->
34                        <input id="AreaUnits" type="hidden" value="<%=AreaUnits %>"/>
35                        </td>
36        <td>&nbsp;</td>
37      </tr>
38      <!-- 显示测量结果的表格行 -->
39      <tr id="MeasureToolbar_BodyRow" >
40       <td  id="MeasureToolbar_BodyCell" style="background-image:url(images/blank.gif);vertical-align:top;padding-left:5px;padding-top:5px;">
41    
42                <table id="MeasureToolbarTable" cellspacing="2" cellpadding="1" style=" width: 100%;font: normal 7pt Verdana; ">
43                    <tr><td style="background-color: #ffffff" id="MeasureDisplay" colspan="2"  valign="top">
44                        在地图上点击画线,双击鼠标结束画线
45                    </td></tr>
46                </table>
47
48            </td>
49            <td id="MeasureToolbar_SideResizeCell" ><img width="5px" height="100%" src="images/blank.gif" alt="" /></td>
50      </tr>
51    </table></td>
52  </tr>
53  <tr id="MeasureToolbar_ResizeRow">
54            <td ><img height="5px" width="100%" src="images/blank.gif" alt="" /></td>
55            <td><img width="5px" src="images/blank.gif" alt="" /></td>
56        </tr>
57</table>
58
59<script language="javascript" type="text/javascript">
60        //回调脚本段
61        var measureVectorCallbackFunctionString = "<%=m_callbackInvocation %>";
62        //根据浏览器的不同设置相应的图片显示
63        if (isIE && ieVersion<7)
64        {
65           setIE6MeasureToolbarImages(); 
66        }
  
67
</script>
68
6.在完成上面的代码后,就把这个用户控件拖到Default.aspx页面中,并且设置相应的属性,具体设置好后的代码如下:
1<uc1:Measure id="Measure1" runat="server" AreaUnits="Sq_Miles" MapBuddyId="Map1" MapUnits="Resource_Default" MeasureUnits="Meters" NumberDecimals="3">
2</uc1:Measure>
7
. 在Toolbar1中新增加一个Tool,设置相应的属性,如果设置后代码如下:
1<esri:Tool ClientAction="startMeasure()" DefaultImage="~/images/measure.png" HoverImage="~/images/measure_HOVER.gif" JavaScriptFile="" Name="Measure" SelectedImage="~/images/measure_ON.gif" Text="Measure" ToolTip="Measure" />
8
.接下来实现ClientAction的startMeasure()的js方法,在javascript目录中新建display_measure.js文件,同时在Measure.ascx文件中添加对这个js文件的引用。
1<script language="javascript" type="text/javascript" src="JavaScript/display_measure.js"></script>
9.在js文件中编写startMeasure()方法,代码和说明如下:
  1//测量控件的内容显示,必须定义为m_measureDisplay,在Esri的display_dotnetadf.js的processCallbackResult的方法中有用到
  2var m_measureDisplay = "MeasureDisplay";
  3//测量控件的状态
  4var m_currentMeasureToolbarTool = "polyline";
  5
  6//测量类型
  7var m_MeasureTypes = new Array();
  8m_MeasureTypes[0= "point";
  9m_MeasureTypes[1= "polyline";
 10m_MeasureTypes[2= "polygon";
 11
 12//
 13function startMeasure() {
 14    var md;
 15    // 获取测量控件的内容显示
 16    if (m_measureDisplay!=null{
 17        md = document.getElementById(m_measureDisplay);
 18    }

 19    
 20    if (m_currentMeasureToolbarTool=="point")//
 21    {
 22        if (md!=null)
 23        {
 24           //设置信息提示
 25           md.innerHTML = "Click on the map to return the coordinate location of the point.<br />";
 26        }
 
 27        //点状态初始化方法
 28        MeasurePoint(map.controlName);
 29    }
 
 30    else if (m_currentMeasureToolbarTool=="polyline")//线
 31    {
 32        if (md!=null)
 33        {
 34           md.innerHTML = "Click on the map and draw a line. Double-click to end the line.<br />";
 35        }

 36        //线状态初始化方法
 37        MeasurePolyline(map.controlName);
 38    }
 
 39    else//
 40    {
 41        if (md!=null)
 42        {
 43           md.innerHTML = "Click on the map and draw a polygon. Double-click to end the polygon.<br />";
 44        }

 45        //面状态初始化方法
 46        MeasurePolygon(map.controlName);
 47    }

 48}

 49
 50
 51function MeasurePoint(divid) {
 52    map = Maps[divid];
 53    if (map!=null)
 54    {
 55        //显示的容器,Esri的display_map.js中有定义
 56        vectortoolbar = "MeasureToolbar";
 57        //setTool方法Esri的display_map.js中有定义,参数说明(模式,是否显示载入中提示,客户端函数,鼠标指针,vectorMode等于-1时不显示,vectortoolbar是否显示,浏览器状态栏显示内容,是否清除DrawnVectors,客户端回调脚本)
 58        map.setTool("Measure"false"Point""pointer"-1"visible","");
 59        
 60        map.divObject.onmousedown = MapCoordsClick;
 61        map.mode = "MeasurePoint";
 62        var vo = map.vectorObject;
 63        //显示vectorObject
 64        showLayer(vo.divId);
 65        //先清除原来的
 66        vo.clear();
 67        //把点画上去
 68        vo.draw();
 69    }
    
 70}

 71
 72function MeasurePolyline(divid) 
 73{
 74    map = Maps[divid];
 75    if (map!=null
 76    {
 77        //回调客户端脚本段,WebForm_DoCallback('ctl02',argument,processCallbackResult,context,null,true)
 78        map.vectorCallbackFunctionString = measureVectorCallbackFunctionString;
 79        //显示的容器,Esri的display_map.js中有定义
 80        vectortoolbar = "MeasureToolbar";
 81        //setTool方法Esri的display_map.js中有定义,参数说明(模式,是否显示载入中提示,客户端函数,鼠标指针,vectorMode等于-1时不显示线条,vectortoolbar是否显示,浏览器状态栏显示内容,是否清除DrawnVectors,客户端回调脚本)
 82        map.setTool("Measure"false"ClickShape""crosshair"1"visible""Measure-Polyline - Click to start line. Click again to add vectors. Double-click to add last vector and complete polyline."false, measureVectorCallbackFunctionString);
 83    }

 84}

 85
 86function MeasurePolygon(divid) 
 87{
 88    map = Maps[divid];
 89    if (map!=null
 90    {
 91        //回调客户端脚本段,WebForm_DoCallback('ctl02',argument,processCallbackResult,context,null,true)
 92        map.vectorCallbackFunctionString = measureVectorCallbackFunctionString;
 93        //显示的容器,Esri的display_map.js中有定义
 94        vectortoolbar = "MeasureToolbar";
 95        map.setTool("Measure"false"ClickShape""crosshair"2"visible""Measure-Polygon - Click to start line. Click again to add vectors. Double-click to add last vector and complete polygon."false, measureVectorCallbackFunctionString);
 96    }

 97}

 98
 99//
100function MapCoordsClick(e) 
101{
102    var vo = map.vectorObject;
103    var pix = vo.pixelObject;
104    var xycoord = vo.xyCoord;
105    getXY(e);
106    zleft = mouseX - map.containerLeft;
107    ztop = mouseY - map.containerTop;
108    vo.clear();
109    vo.crosshair(zleft, ztop);
110    vo.draw();
111
112    map.xMin=zleft;
113    map.yMin=ztop;
114    map.getTopLeftTile();
115    coordString = + zleft + ":" + ztop;
116    var argument = "ControlID=" + map.controlName + "&EventArg=Point&ControlType=Map&coords=" + coordString + "&VectorMode=Measure&VectorAction=Coordinates&minx=" + zleft + "&miny=" + ztop;
117    if(checkForFormElement(document, 0"MeasureUnits"))
118    {
119       argument += "&MeasureUnits=" + document.forms[0].MeasureUnits.value;
120    }

121    if(checkForFormElement(document, 0"AreaUnits")) 
122    {
123       argument += "&AreaUnits=" + document.forms[0].AreaUnits.value;
124    }

125    if(checkForFormElement(document, 0"MapUnits")) 
126    {
127       argument += "&MapUnits=" + document.forms[0].MapUnits.options[document.forms[0].MapUnits.selectedIndex].value;
128    }

129    var context = map.controlName + ",Point";
130    map.vectorCallbackFunctionString = measureVectorCallbackFunctionString;
131    eval(map.vectorCallbackFunctionString);
132
133}
10.在js文件中添加测量工具的checkMeasureToolbarBorde方法和setMeasureToolbarTool方法,代码和说明如下:
 1//测量按钮鼠标移上去的显示效果
 2function checkMeasureToolbarBorder(cell, type) 
 3{
 4    if (type.toLowerCase()==m_currentMeasureToolbarTool)
 5    {
 6       cell.style.borderColor = "Black";
 7    }
  
 8    else
 9    {
10       cell.style.borderColor = "White";  
11    }

12        
13}

14
15//测量按钮切换
16function setMeasureToolbarTool(type) 
17{
18    m_currentMeasureToolbarTool = type.toLowerCase();
19    var cellObj;
20    var buttonId = "";
21    //显示状态切换
22    for(var i=0; i<m_MeasureTypes.length; i++
23    {
24        buttonId = "MeasureToolbarButton_" + m_MeasureTypes[i];
25        cellObj = document.getElementById(buttonId);
26        if (cellObj!=null
27        {
28            if (m_MeasureTypes[i]==m_currentMeasureToolbarTool) 
29            {
30                cellObj.style.borderColor = "Black";
31                cellObj.style.backgroundColor = "#EEEEEE";
32                startMeasure();
33            }

34            else 
35            {
36                cellObj.style.borderColor = "White";
37                cellObj.style.backgroundColor = "White";
38            }

39        }

40    }

41}
11.接下来添加测量控件的拖拽事件dragMeasureToolbarStart具体的代码和说明如下:
 1//测量控件拖拽开始
 2function dragMeasureToolbarStart(e, id) 
 3{
 4    if (id!=null) m_measureToolbarId = id;
 5    m_measureToolbar = document.getElementById(m_measureToolbarId);
 6    if (m_measureToolbar!=null
 7    {
 8        getXY(e);
 9        var box = calcElementPosition(m_measureToolbarId);
10        m_measureXOffset = mouseX - box.left;
11        m_measureYOffset = mouseY - box.top;
12    }

13    m_measureMoveFunction = document.onmousemove; 
14    document.onmousemove = dragMeasureToolbarMove;
15    document.onmouseup = dragMeasureToolbarStop;
16    return false;
17}

18
19//测量控件拖拽移动
20function dragMeasureToolbarMove(e) 
21{
22    getXY(e);
23    m_measureToolbar.style.left = (mouseX-m_measureXOffset) + "px";;
24    m_measureToolbar.style.top = (mouseY-m_measureYOffset) + "px";
25    return false;
26}

27
28//测量控件拖拽停止
29function dragMeasureToolbarStop(e) 
30{
31    document.onmousemove = m_measureMoveFunction;
32    document.onmouseup = null;
33    return false;
34}
12.到这里这个Common_WebMappingAppCSharp.zip示例大体上分析完成了,剩下的就是一些比较简单的功能这样也不作分析了。

posted @ 2009-08-26 11:29  刘阳  阅读(631)  评论(0编辑  收藏  举报