PageRenderTime 48ms CodeModel.GetById 10ms RepoModel.GetById 0ms app.codeStats 1ms

/GeoRouting/branches/SharpMapUITest/SharpMapUITest/MapDisplay.cs

http://georouting-hyperpath.googlecode.com/
C# | 1002 lines | 705 code | 141 blank | 156 comment | 92 complexity | e3b9834c87d361df25d176ea91a595b7 MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-2.1
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Drawing;
  5. using System.Linq;
  6. using System.Windows.Forms;
  7. using Npgsql;
  8. using System.Drawing.Drawing2D;
  9. using SharpMap.Forms;
  10. using SharpMap.Data;
  11. using SharpMap.Data.Providers;
  12. using SharpMap.Layers;
  13. using System.Collections.ObjectModel;
  14. using System.Diagnostics;
  15. using System.IO;
  16. using GisSharpBlog.NetTopologySuite;
  17. using System.Drawing.Imaging;
  18. namespace SharpMapUITest
  19. {
  20. public partial class MapDisplay : Form
  21. {
  22. public MapDisplay()
  23. {
  24. InitializeComponent();
  25. }
  26. private static string database = "postgis";
  27. //Default connection
  28. public static string ConnStr = "Server=localhost"
  29. + ";DataBase=" + database
  30. + ";Port=5432"
  31. + ";Userid= postgres"
  32. + ";password=password"
  33. + ";Protocol=3;SSL=false;Pooling=true;MinPoolSize=1;MaxPoolSize=20;EnCoding=UNICODE;Timeout=15;SslMode=Disable";
  34. SharpMap.Layers.LabelLayer verticesAsLabel;//node label style
  35. SharpMap.Layers.LabelLayer roadlayASLabel;//link label style
  36. public int[] Nodes_Animation;
  37. public int[] Links_Animation;
  38. Graphics g;
  39. int timecounter = 0;
  40. double fullzoom = 0;
  41. private void Form1_Load(object sender, EventArgs e)
  42. {
  43. //?????????????????????
  44. using (NpgsqlConnection conn = new NpgsqlConnection(ConnStr))
  45. {
  46. string QueryGeometricLayers = "SELECT f_table_name FROM geometry_columns;";
  47. conn.Open();
  48. NpgsqlCommand cmd = new NpgsqlCommand();
  49. cmd.Connection = conn;
  50. cmd.CommandType = CommandType.Text;
  51. cmd.CommandText = QueryGeometricLayers;
  52. NpgsqlDataReader dr = cmd.ExecuteReader();
  53. while (dr.Read())
  54. {
  55. Layers_clb.Items.Add(dr["f_table_name"].ToString());
  56. }
  57. dr.Dispose();
  58. cmd.Dispose();
  59. }
  60. g = mapImage1.CreateGraphics();
  61. mapImage1.MouseEnter += new EventHandler(Map_MouseEnterEventHandler);
  62. mapImage1.ZoomOnDblClick = true;
  63. }
  64. private SharpMap.Map GetCurrentMap(string sqlconn, string[] tableName)
  65. {
  66. SharpMap.Map myMap = new SharpMap.Map();
  67. using (NpgsqlConnection conn = new NpgsqlConnection(sqlconn))
  68. {
  69. conn.Open();
  70. myMap.Size = new System.Drawing.Size(this.mapImage1.Size.Width, this.mapImage1.Height);
  71. //myMap.MinimumZoom = 10;
  72. if (tableName.Contains("vertices_tmp"))
  73. {
  74. //Add node layer
  75. verticesAsLabel = new SharpMap.Layers.LabelLayer("nodes");
  76. SharpMap.Layers.VectorLayer vertices_tmp = new SharpMap.Layers.VectorLayer("vertices_tmp");
  77. vertices_tmp.DataSource = new SharpMap.Data.Providers.PostGIS(conn.ConnectionString, "vertices_tmp", "the_geom");
  78. vertices_tmp.Style.Symbol = SharpMap.Styles.VectorStyle.DefaultSymbol;
  79. //vertices_tmp.Style.Symbol = Image.FromFile("..\\..\\Node.bmp");
  80. vertices_tmp.Style.SymbolScale = (float)0.32;
  81. //?????
  82. vertices_tmp.SmoothingMode = SmoothingMode.None;
  83. myMap.Layers.Add(vertices_tmp);
  84. //????Label???
  85. verticesAsLabel.DataSource = vertices_tmp.DataSource;
  86. verticesAsLabel.LabelColumn = "id";
  87. verticesAsLabel.Style.Font = new Font("Arial", 6, FontStyle.Bold);
  88. verticesAsLabel.Style = new SharpMap.Styles.LabelStyle();
  89. verticesAsLabel.Style.ForeColor = Color.Red;
  90. verticesAsLabel.Style.Offset = new PointF(10, 0);
  91. verticesAsLabel.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
  92. verticesAsLabel.SmoothingMode = SmoothingMode.AntiAlias;
  93. //layASLabel.SRID = 3945; //This is your spatial ref no
  94. verticesAsLabel.LabelFilter = SharpMap.Rendering.LabelCollisionDetection.ThoroughCollisionDetection;
  95. verticesAsLabel.Style.CollisionDetection = true;
  96. }
  97. if (tableName.Contains("road"))
  98. {
  99. roadlayASLabel = new SharpMap.Layers.LabelLayer("road");
  100. //??road?????????
  101. SharpMap.Layers.VectorLayer road = new SharpMap.Layers.VectorLayer("road");
  102. road.DataSource = new SharpMap.Data.Providers.PostGIS(conn.ConnectionString, "road", "the_geom");
  103. //conn.Open();
  104. //var indexes = road.DataSource.GetObjectIDsInView(road.DataSource.GetExtents());
  105. road.Style.Line = new System.Drawing.Pen(System.Drawing.Color.LightBlue, 1);
  106. //?????
  107. road.SmoothingMode = SmoothingMode.None;
  108. myMap.Layers.Add(road);
  109. //????Label???
  110. roadlayASLabel.DataSource = road.DataSource;
  111. roadlayASLabel.LabelColumn = "gid";
  112. roadlayASLabel.Style.Font = new Font("Arial", 6, FontStyle.Bold);
  113. roadlayASLabel.Style = new SharpMap.Styles.LabelStyle();
  114. roadlayASLabel.Style.ForeColor = Color.Black;
  115. roadlayASLabel.Style.Offset = new PointF(10, 0);
  116. roadlayASLabel.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
  117. roadlayASLabel.SmoothingMode = SmoothingMode.AntiAlias;
  118. //layASLabel.SRID = 3945; //This is your spatial ref no
  119. roadlayASLabel.LabelFilter = SharpMap.Rendering.LabelCollisionDetection.ThoroughCollisionDetection;
  120. roadlayASLabel.Style.CollisionDetection = true;
  121. }
  122. if (tableName.Contains("hyperpath_lyr"))
  123. {
  124. //??hyperpath_lyr?????????
  125. SharpMap.Layers.VectorLayer hyperpath = new SharpMap.Layers.VectorLayer("hyperpath_lyr");
  126. hyperpath.DataSource = new SharpMap.Data.Providers.PostGIS(conn.ConnectionString, "hyperpath_lyr", "the_geom");
  127. hyperpath.Style.Line = new System.Drawing.Pen(System.Drawing.Color.GreenYellow, 5);
  128. myMap.Layers.Add(hyperpath);
  129. //????
  130. SharpMap.Styles.VectorStyle firstStyle = new SharpMap.Styles.VectorStyle();
  131. SharpMap.Styles.VectorStyle lastStyle = new SharpMap.Styles.VectorStyle();
  132. firstStyle.Line = new System.Drawing.Pen(System.Drawing.Color.Green, 1);
  133. lastStyle.Line = new System.Drawing.Pen(System.Drawing.Color.Blue, 5);
  134. //firstStyle.Outline = new Pen(Color.Black);
  135. //firstStyle.EnableOutline = true;
  136. //lastStyle.Outline = new Pen(Color.Black);
  137. //lastStyle.EnableOutline = true;
  138. SharpMap.Rendering.Thematics.GradientTheme Theme = new SharpMap.Rendering.Thematics.GradientTheme("choice_possibility", 0, 1, firstStyle, lastStyle);
  139. //Theme.FillColorBlend = SharpMap.Rendering.Thematics.ColorBlend.ThreeColors(Color.Yellow, Color.SkyBlue, Color.HotPink);
  140. hyperpath.Theme = Theme;
  141. }
  142. if (tableName.Contains("popath_lyr"))
  143. {
  144. //??road?????????
  145. SharpMap.Layers.VectorLayer popath_lyr = new SharpMap.Layers.VectorLayer("popath_lyr");
  146. popath_lyr.DataSource = new SharpMap.Data.Providers.PostGIS(conn.ConnectionString, "popath_lyr", "the_geom");
  147. //conn.Open();
  148. //var indexes = road.DataSource.GetObjectIDsInView(road.DataSource.GetExtents());
  149. popath_lyr.Style.Line = new System.Drawing.Pen(System.Drawing.Color.LightBlue, 1);
  150. //?????
  151. popath_lyr.SmoothingMode = SmoothingMode.None;
  152. SharpMap.Styles.VectorStyle mystyle = new SharpMap.Styles.VectorStyle();
  153. mystyle.Line.Color = Color.Blue;
  154. mystyle.Line.Width = 2.0f;
  155. popath_lyr.Style = mystyle;
  156. myMap.Layers.Add(popath_lyr);
  157. }
  158. if (tableName.Contains("regretpath_lyr"))
  159. {
  160. //??road?????????
  161. SharpMap.Layers.VectorLayer regretpath_lyr = new SharpMap.Layers.VectorLayer("regretpath_lyr");
  162. regretpath_lyr.DataSource = new SharpMap.Data.Providers.PostGIS(conn.ConnectionString, "regretpath_lyr", "the_geom");
  163. //conn.Open();
  164. //var indexes = road.DataSource.GetObjectIDsInView(road.DataSource.GetExtents());
  165. regretpath_lyr.Style.Line = new System.Drawing.Pen(System.Drawing.Color.LightBlue, 1);
  166. //?????
  167. regretpath_lyr.SmoothingMode = SmoothingMode.None;
  168. SharpMap.Styles.VectorStyle mystyle = new SharpMap.Styles.VectorStyle();
  169. mystyle.Line.Color = Color.Red;
  170. mystyle.Line.Width = 3.5f;
  171. regretpath_lyr.Style = mystyle;
  172. myMap.Layers.Add(regretpath_lyr);
  173. }
  174. }
  175. return myMap;
  176. }
  177. #region ToolStripButton Events
  178. private void Refresth_btn_Click(object sender, EventArgs e)
  179. {
  180. timer1.Dispose();
  181. if (ConnStr == string.Empty) MessageBox.Show("No Sql Connection!");
  182. List<string> lyrs = new List<string>();
  183. foreach (var i in Layers_clb.Items)
  184. {
  185. if(Layers_clb.CheckedItems.Contains(i))
  186. lyrs.Add(i.ToString());
  187. }
  188. CurrentDB_tsl.Text = "Connection: localhost//"+database;
  189. //mapImage1.Map.Size = Size;
  190. mapImage1.Map = GetCurrentMap(ConnStr, lyrs.ToArray());
  191. Cursor = Cursors.Default;
  192. mapImage1.ActiveTool = MapImage.Tools.None;
  193. //mapImage1.ActiveTool = MapImage.Tools.Pan;
  194. mapImage1.Map.ZoomToExtents();
  195. fullzoom = mapImage1.Map.Zoom;
  196. //mapImage1.Map.GetMap();
  197. SelectedLayer_tsl.Text = "Current Layer: "+Layers_clb.SelectedItem.ToString();
  198. //mapImage1.Cursor = mic;
  199. mapImage1.Refresh();
  200. }
  201. private void mapImage1_SizeChanged(object sender, EventArgs e)
  202. {
  203. if (mapImage1.Size.Width != 0&&mapImage1.Size.Height!=0)
  204. mapImage1.Refresh();
  205. }
  206. //private void DrawRectange(System.Drawing.PointF start, System.Drawing.PointF end, Graphics g)
  207. //{
  208. // g.DrawRectangle(new Pen(Color.Red), start.X, start.Y, start.X - end.X, start.Y - end.Y);
  209. //}
  210. private void ShowNodeLabel_btn_Click(object sender, EventArgs e)
  211. {
  212. if (Layers_clb.CheckedItems.Contains("vertices_tmp"))
  213. verticesAsLabel.Render(g, mapImage1.Map);
  214. }
  215. private void ShowLinkLabel_btn_Click(object sender, EventArgs e)
  216. {
  217. if (Layers_clb.CheckedItems.Contains("road"))
  218. roadlayASLabel.Render(g, mapImage1.Map);
  219. }
  220. private void ZoomToExtent_Click(object sender, EventArgs e)
  221. {
  222. this.mapImage1.Map.ZoomToExtents();
  223. this.mapImage1.Refresh();
  224. }
  225. private void ZoomIn_btn_Click(object sender, EventArgs e)
  226. {
  227. mapImage1.ActiveTool = MapImage.Tools.ZoomIn;
  228. }
  229. private void ZoomOut_btn_Click(object sender, EventArgs e)
  230. {
  231. mapImage1.ActiveTool = MapImage.Tools.ZoomOut;
  232. }
  233. private void Pan_btn_Click(object sender, EventArgs e)
  234. {
  235. mapImage1.ActiveTool = MapImage.Tools.Pan;
  236. }
  237. private void Query_btn_Click(object sender, EventArgs e)
  238. {
  239. mapImage1.ActiveTool = MapImage.Tools.SelfDefinedQuery;
  240. }
  241. #endregion
  242. #region MapImage1 Events
  243. private void mapImage1_MouseClick(object sender, MouseEventArgs e)
  244. {
  245. if (mapImage1.ActiveTool == MapImage.Tools.SelfDefinedQuery)
  246. {
  247. PointF p = new PointF(e.X, e.Y);
  248. var pos = mapImage1.Map.ImageToWorld(p);
  249. double allowedAccuracy = mapImage1.Map.PixelSize * 5;
  250. string lyrName=Layers_clb.SelectedItem.ToString();
  251. var QueryLayer = mapImage1.Map.Layers[lyrName] as SharpMap.Layers.VectorLayer;
  252. SharpMap.Data.FeatureDataRow QueryResult = null;
  253. if (QueryLayer is SharpMap.Layers.ICanQueryLayer)
  254. {
  255. QueryResult = PickUpGeometry(pos, QueryLayer, allowedAccuracy);
  256. }
  257. if (QueryResult != null)
  258. {
  259. mapImage1.Refresh();
  260. RenderFeatureDataRow(QueryResult, g, Color.Blue, Color.Orange);
  261. DataRow dr = QueryResult as DataRow;
  262. SelectedItem_tsl.Text = "Selected Geometry: "+QueryResult.Geometry.GeometryType.ToString() +" GID = "+dr[0].ToString();
  263. }
  264. else SelectedItem_tsl.Text = "No item is selected";
  265. }
  266. }
  267. private void mapImage1_MouseMove(SharpMap.Geometries.Point WorldPos, MouseEventArgs ImagePos)
  268. {
  269. Status_tsl.Text = string.Format("WCRS: X: {0}, Y:{1}", WorldPos.X, WorldPos.Y);
  270. }
  271. #endregion
  272. #region Defined Function
  273. //?NetTopologySuite????????????
  274. SharpMap.Data.FeatureDataRow PickUpGeometry(SharpMap.Geometries.Point pos, SharpMap.Layers.VectorLayer layer, double amountGrow)
  275. {
  276. SharpMap.Geometries.BoundingBox bbox = pos.GetBoundingBox().Grow(amountGrow);
  277. SharpMap.Data.FeatureDataSet ds = new SharpMap.Data.FeatureDataSet();
  278. layer.DataSource.ExecuteIntersectionQuery(bbox, ds);
  279. DataTable tbl = ds.Tables[0] as SharpMap.Data.FeatureDataTable;
  280. dataGridView1.DataSource = tbl;
  281. GisSharpBlog.NetTopologySuite.IO.WKTReader reader = new GisSharpBlog.NetTopologySuite.IO.WKTReader();
  282. GeoAPI.Geometries.IGeometry point = reader.Read(pos.ToString());
  283. //??????????????
  284. if (tbl.Rows.Count == 0)
  285. return null;
  286. double distance = point.Distance(reader.Read((tbl.Rows[0] as SharpMap.Data.FeatureDataRow).Geometry.ToString()));
  287. SharpMap.Data.FeatureDataRow selectedFeature = tbl.Rows[0] as SharpMap.Data.FeatureDataRow;
  288. //????????1????????????????
  289. if (tbl.Rows.Count > 1)
  290. for (int i = 1; i < tbl.Rows.Count; i++)
  291. {
  292. GeoAPI.Geometries.IGeometry line = reader.Read((tbl.Rows[i] as SharpMap.Data.FeatureDataRow).Geometry.ToString());
  293. if (point.Distance(line) < distance)
  294. {
  295. distance = point.Distance(line);
  296. selectedFeature = tbl.Rows[i] as SharpMap.Data.FeatureDataRow;
  297. }
  298. }
  299. return selectedFeature;
  300. }
  301. //??????
  302. private void RenderGeometry(SharpMap.Geometries.IGeometry item, string type)
  303. {
  304. if(type=="Point")
  305. SharpMap.Rendering.VectorRenderer.DrawPoint(g, item as SharpMap.Geometries.Point, new SolidBrush(Color.Red), 10f, new PointF(0f, 0f), mapImage1.Map);
  306. else if(type=="Polygon")
  307. {
  308. Brush brush = new SolidBrush(Color.FromArgb(20, Color.Brown));
  309. SharpMap.Rendering.VectorRenderer.DrawPolygon(g, item as SharpMap.Geometries.Polygon, brush , new Pen(Color.Brown),true, mapImage1.Map);
  310. }
  311. }
  312. //?????
  313. private void RenderFeatureDataRow(SharpMap.Data.FeatureDataRow item,Graphics g,Color PointColor,Color PolyLineColor)
  314. {
  315. //Graphics g = mapImage1.CreateGraphics();
  316. //if (PointColor == null) PointColor = Color.Blue;
  317. //if (PolyLineColor == null) PolyLineColor = Color.Orange;
  318. Font aFont = new Font("Times New Roman", 18, FontStyle.Regular | FontStyle.Regular);
  319. switch (item.Geometry.GeometryType)
  320. {
  321. case SharpMap.Geometries.GeometryType2.Point:
  322. SharpMap.Rendering.VectorRenderer.DrawPoint(g, item.Geometry as SharpMap.Geometries.Point, new SolidBrush(PointColor), 6f, new PointF(0f, 0f), mapImage1.Map);
  323. // render label at the same time
  324. //PointF pos = mapImage1.Map.WorldToImage(item.Geometry as SharpMap.Geometries.Point);
  325. //SharpMap.Rendering.VectorRenderer.DrawLabel(g, pos, new PointF(2f, 2f), aFont, Color.Black, new SolidBrush(Color.Empty), new Pen(new SolidBrush(Color.Empty)), 0f, item["id"].ToString(), mapImage1.Map);
  326. aFont.Dispose();
  327. break;
  328. //case SharpMap.Geometries.GeometryType2.LineString:
  329. // SharpMap.Rendering.VectorRenderer.DrawLineString(g, item.Geometry as SharpMap.Geometries.LineString, new Pen(Color.Orange,3), mapImage1.Map);
  330. // break;
  331. case SharpMap.Geometries.GeometryType2.MultiLineString:
  332. SharpMap.Rendering.VectorRenderer.DrawMultiLineString(g, item.Geometry as SharpMap.Geometries.MultiLineString, new Pen(PolyLineColor,1.5f), mapImage1.Map, 0f);
  333. // render label at the same time
  334. //SharpMap.Geometries.MultiLineString multiline=item.Geometry as SharpMap.Geometries.MultiLineString;
  335. //var p=multiline.LineStrings[multiline.LineStrings.Count / 2].Vertices;
  336. //PointF pos2 = mapImage1.Map.WorldToImage(p[p.Count/2]);
  337. //SharpMap.Rendering.VectorRenderer.DrawLabel(g, pos2, new PointF(2f, 2f), aFont, Color.Black, new SolidBrush(Color.Empty), new Pen(new SolidBrush(Color.Empty)), 0f, item["gid"].ToString(), mapImage1.Map);
  338. //aFont.Dispose();
  339. break;
  340. default:
  341. MessageBox.Show(this, "Error", "Render doesn't support this type of geometry", MessageBoxButtons.OK, MessageBoxIcon.Error);
  342. break;
  343. }
  344. }
  345. //??????????
  346. private void RenderFeatureDataTable(SharpMap.Data.FeatureDataTable table)
  347. {
  348. foreach (FeatureDataRow item in table.Rows)
  349. {
  350. RenderFeatureDataRow(item, g, Color.Blue, Color.Orange);
  351. }
  352. }
  353. //????ID???Geometry
  354. private void RenderElementByID(int _id,Color _PointColor,string _type,bool _refresh,Graphics g)
  355. {
  356. SharpMap.Layers.VectorLayer query_lyr;
  357. if (_type == "Point")
  358. query_lyr = this.mapImage1.Map.GetLayerByName("Vertices_tmp") as SharpMap.Layers.VectorLayer;
  359. else
  360. query_lyr = this.mapImage1.Map.GetLayerByName("road") as SharpMap.Layers.VectorLayer;
  361. if (query_lyr == null)
  362. {
  363. throw (new ApplicationException("An attempt was made to read from a closed datasource"));
  364. }
  365. if (!query_lyr.DataSource.IsOpen) query_lyr.DataSource.Open();
  366. //get all the features in the query_lyr.
  367. SharpMap.Data.FeatureDataSet ds = new SharpMap.Data.FeatureDataSet();
  368. query_lyr.DataSource.ExecuteIntersectionQuery(query_lyr.Envelope, ds);
  369. query_lyr.DataSource.Close();
  370. if (ds == null) return;
  371. //hignlight the geometry
  372. //SharpMap.Layers.VectorLayer selectedLyr = new SharpMap.Layers.VectorLayer("selectedLyr");
  373. if (_type == "Point")
  374. {
  375. DataRow[] query = ds.Tables[0].Select("","id");
  376. //EnumerableRowCollection<DataRow> query = from id in ds.Tables[0].AsEnumerable()
  377. // orderby id.Field<int>("id")
  378. // select id;
  379. FeatureDataRow fdr = query.ElementAt(_id - 1) as FeatureDataRow;
  380. if (_refresh)
  381. {
  382. mapImage1.Map.Center = fdr.Geometry as SharpMap.Geometries.Point;
  383. mapImage1.Refresh();
  384. }
  385. RenderFeatureDataRow(fdr, g, _PointColor, Color.Orange);
  386. //selectedLyr.DataSource = new SharpMap.Data.Providers.GeometryProvider(fdr);
  387. }
  388. else if (_type == "PolyLine")
  389. {
  390. DataRow[] query = ds.Tables[0].Select("", "gid");
  391. //EnumerableRowCollection<DataRow> query = from id in ds.Tables[0].AsEnumerable()
  392. // orderby id.Field<int>("gid")
  393. // select id;
  394. FeatureDataRow fdr = query.ElementAt(_id - 1) as FeatureDataRow;
  395. var multiline = fdr.Geometry as SharpMap.Geometries.MultiLineString;
  396. var p = multiline.LineStrings[multiline.LineStrings.Count / 2].Vertices;
  397. if (_refresh)
  398. {
  399. mapImage1.Map.Center = p[p.Count / 2];
  400. mapImage1.Refresh();
  401. }
  402. RenderFeatureDataRow(fdr, g, _PointColor, Color.Orange);
  403. }
  404. #region ????????????????????????????
  405. /*
  406. selectedLyr.Style.EnableOutline = true;
  407. selectedLyr.Style.Outline = new Pen(Color.GreenYellow, 5);
  408. selectedLyr.Style.PointColor = new SolidBrush(_color);
  409. selectedLyr.Style.Fill = new SolidBrush(Color.Transparent);
  410. //selectedLyr.Style.Fill = new SolidBrush(_color);
  411. selectedLyr.SRID = 2450;
  412. //set the zoom of map
  413. this.mapImage1.Map.Layers.Add(selectedLyr);
  414. //this.mapImage1.Map.ZoomToBox(ds.Tables[0][rowID].Geometry.GetBoundingBox());
  415. mapImage1.Map.GetMap();
  416. mapImage1.Refresh();
  417. */
  418. #endregion
  419. }
  420. //private void RenderNodeByGID_GDI(int _id, Color _color)
  421. //{
  422. // SharpMap.Layers.VectorLayer query_lyr = this.mapImage1.Map.GetLayerByName("Vertices_tmp") as SharpMap.Layers.VectorLayer;
  423. // if (query_lyr == null)
  424. // {
  425. // throw (new ApplicationException("An attempt was made to read from a closed datasource"));
  426. // }
  427. // if (!query_lyr.DataSource.IsOpen) query_lyr.DataSource.Open();
  428. // //get all the features in the query_lyr.
  429. // SharpMap.Data.FeatureDataSet ds = new SharpMap.Data.FeatureDataSet();
  430. // query_lyr.DataSource.ExecuteIntersectionQuery(query_lyr.Envelope, ds);
  431. // query_lyr.DataSource.Close();
  432. // if (ds == null) return;
  433. // else
  434. // {
  435. // foreach (DataRow i in ds.Tables[0])
  436. // {
  437. // FeatureDataRow feature = i as FeatureDataRow;
  438. // if(feature.Geometry.)
  439. // }
  440. // }
  441. //}
  442. private void StartAnimation()
  443. {
  444. timer1.Interval = 2;
  445. timer1.Start();
  446. }
  447. private void PauseAnimation()
  448. {
  449. timer1.Stop();
  450. }
  451. #endregion
  452. //????????????????
  453. private void Redirect_cmb_SelectedIndexChanged(object sender, EventArgs e)
  454. {
  455. switch (Redirect_cmb.SelectedIndex)
  456. {
  457. case 0: database = "postgis";
  458. CurrentDB_tsl.Text = "Connection: //localhost/"+database;
  459. break;
  460. case 1: database="postgis2";
  461. CurrentDB_tsl.Text = "Connection: //localhost/" + database;
  462. break;
  463. case 2:
  464. database = "postgis3";
  465. CurrentDB_tsl.Text = "Connection: //localhost/" + database;
  466. break;
  467. case 3:
  468. database = "postgis4";
  469. CurrentDB_tsl.Text = "Connection: //localhost/" + database;
  470. break;
  471. default:
  472. break;
  473. }
  474. ConnStr = "Server=localhost"
  475. + ";DataBase=" + database
  476. + ";Port=5432"
  477. + ";Userid= postgres"
  478. + ";password=password"
  479. + ";Protocol=3;SSL=false;Pooling=true;MinPoolSize=1;MaxPoolSize=20;EnCoding=UNICODE;Timeout=15;SslMode=Disable";
  480. }
  481. //??ID???
  482. private void FindGeometry_btn_Click_1(object sender, EventArgs e)
  483. {
  484. int i = -1;
  485. int.TryParse(NodeInput_tb.Text.Trim(), out i);
  486. if (i != -1)
  487. {
  488. if (Layers_clb.SelectedItem.ToString() == "vertices_tmp")
  489. RenderElementByID(i, Color.Blue, "Point",true,g);
  490. else if (Layers_clb.SelectedItem.ToString() == "road")
  491. RenderElementByID(i, Color.Blue, "PolyLine",true,g);
  492. }
  493. }
  494. //?????????
  495. private void timer1_Tick(object sender, EventArgs e)
  496. {
  497. if (timecounter < Nodes_Animation.Length)
  498. {
  499. RenderElementByID(Nodes_Animation[timecounter], Color.Blue, "Point",false,g);
  500. }
  501. if (timecounter < Links_Animation.Length)
  502. {
  503. RenderElementByID(Links_Animation[timecounter], Color.Blue, "PolyLine",false,g);
  504. Animation_trackbar.Value = timecounter;
  505. timecounter++;
  506. }
  507. else
  508. {
  509. timer1.Stop();
  510. timecounter = 0;
  511. Animation_trackbar.Value = 0;
  512. mapImage1.Refresh();
  513. }
  514. }
  515. //??????
  516. private void Start_btn_Click(object sender, EventArgs e)
  517. {
  518. Animation_trackbar.Maximum = Links_Animation.Length;
  519. StartAnimation();
  520. }
  521. //????
  522. private void Pause_btn_Click(object sender, EventArgs e)
  523. {
  524. PauseAnimation();
  525. }
  526. //????
  527. private void Stop_btn_Click(object sender, EventArgs e)
  528. {
  529. timer1.Stop();
  530. timer1.Dispose();
  531. //mapImage1.Map.Layers.Clear();
  532. mapImage1.Refresh();
  533. }
  534. //????_lyr?????_geom?????
  535. private SharpMap.Geometries.MultiPoint GetIntersections(SharpMap.Geometries.Geometry _geom, SharpMap.Layers.ILayer _lyr)
  536. {
  537. SharpMap.Data.FeatureDataSet ds = new SharpMap.Data.FeatureDataSet();
  538. //???????GeoAPI???
  539. GisSharpBlog.NetTopologySuite.IO.WKTReader reader = new GisSharpBlog.NetTopologySuite.IO.WKTReader();
  540. GeoAPI.Geometries.IGeometry polygon = reader.Read(_geom.ToString());
  541. //??_lyr????????????GeoAPI???
  542. SharpMap.Layers.VectorLayer query_lyr;
  543. query_lyr = this.mapImage1.Map.GetLayerByName("Vertices_tmp") as SharpMap.Layers.VectorLayer;
  544. if (!query_lyr.DataSource.IsOpen) query_lyr.DataSource.Open();
  545. SharpMap.Data.FeatureDataSet ds2 = new SharpMap.Data.FeatureDataSet();
  546. query_lyr.DataSource.ExecuteIntersectionQuery(query_lyr.Envelope, ds2);
  547. query_lyr.DataSource.Close();
  548. if (ds2 == null) return null;
  549. DataRow[] query = ds2.Tables[0].Select("", "id");
  550. FeatureDataTable fdt = ds2.Tables[0];
  551. List<GisSharpBlog.NetTopologySuite.Geometries.Point> points = new List<GisSharpBlog.NetTopologySuite.Geometries.Point>();
  552. foreach (FeatureDataRow i in fdt)
  553. {
  554. GeoAPI.Geometries.IGeometry point = reader.Read(i.Geometry.ToString());
  555. points.Add(point as GisSharpBlog.NetTopologySuite.Geometries.Point);
  556. }
  557. GisSharpBlog.NetTopologySuite.Geometries.MultiPoint multipoints = new GisSharpBlog.NetTopologySuite.Geometries.MultiPoint(points.ToArray());
  558. //GeoAPI????
  559. GisSharpBlog.NetTopologySuite.Geometries.MultiPoint Interpoints = (polygon.Intersection(multipoints)) as GisSharpBlog.NetTopologySuite.Geometries.MultiPoint;
  560. SharpMap.Geometries.MultiPoint mp = SharpMap.Converters.NTS.GeometryConverter.ToSharpMapGeometry(Interpoints) as SharpMap.Geometries.MultiPoint;
  561. //Execute boundingbox intersection query, geometry intersection is not well supported
  562. //(_lyr as SharpMap.Layers.VectorLayer).DataSource.ExecuteIntersectionQuery(_geom.GetBoundingBox(), ds);
  563. return mp;
  564. //SharpMap.Layers.VectorLayer laySelected = new SharpMap.Layers.VectorLayer("Selection");
  565. //laySelected.DataSource = new GeometryProvider(mp);
  566. //laySelected.Style.Fill = new System.Drawing.SolidBrush(System.Drawing.Color.Yellow);
  567. //return laySelected;
  568. }
  569. //?GeoAPI????????
  570. private SharpMap.Geometries.Geometry CreateBuffer(int _id, double distance)
  571. {
  572. SharpMap.Layers.VectorLayer query_lyr;
  573. query_lyr = this.mapImage1.Map.GetLayerByName("Vertices_tmp") as SharpMap.Layers.VectorLayer;
  574. if (!query_lyr.DataSource.IsOpen) query_lyr.DataSource.Open();
  575. //get all the features in the query_lyr.
  576. SharpMap.Data.FeatureDataSet ds = new SharpMap.Data.FeatureDataSet();
  577. query_lyr.DataSource.ExecuteIntersectionQuery(query_lyr.Envelope, ds);
  578. query_lyr.DataSource.Close();
  579. if (ds == null) return null;
  580. DataRow[] query = ds.Tables[0].Select("", "id");
  581. //EnumerableRowCollection<DataRow> query = from id in ds.Tables[0].AsEnumerable()
  582. //orderby id.Field<int>("id")
  583. //fdr???????????????????????
  584. FeatureDataRow fdr = query.ElementAt(_id - 1) as FeatureDataRow;
  585. mapImage1.Map.Center = fdr.Geometry as SharpMap.Geometries.Point;
  586. //???NetTopologySuite??????
  587. GisSharpBlog.NetTopologySuite.IO.WKTReader reader = new GisSharpBlog.NetTopologySuite.IO.WKTReader();
  588. GeoAPI.Geometries.IGeometry point = reader.Read(fdr.Geometry.ToString());
  589. GeoAPI.Geometries.IGeometry BufArea_GeoAPI = point.Buffer(distance);
  590. //?GeoAPI???buffer???Sharpmap???
  591. SharpMap.Geometries.Geometry BufArea_SharpMap = SharpMap.Converters.NTS.GeometryConverter.ToSharpMapGeometry(BufArea_GeoAPI as GisSharpBlog.NetTopologySuite.Geometries.Geometry);
  592. return BufArea_SharpMap;
  593. }
  594. private void bufferToolStripMenuItem_Click(object sender, EventArgs e)
  595. {
  596. SharpMap.Geometries.Geometry bufArea=null;
  597. try
  598. {
  599. bufArea = CreateBuffer(Convert.ToInt16(NodeInput_tb.Text.Trim()), Convert.ToDouble(BufferDistanceToolStripMenuItem.Text.Trim()));
  600. }
  601. catch { MessageBox.Show(this, "Make sure the NodeID(Find Node) and Buffer distance are in right format.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); }
  602. SharpMap.Geometries.BoundingBox box = bufArea.GetBoundingBox();
  603. mapImage1.Map.ZoomToBox(box);
  604. mapImage1.Refresh();
  605. //?????
  606. RenderGeometry(bufArea, "Polygon");
  607. SharpMap.Geometries.MultiPoint intersection = GetIntersections(bufArea, mapImage1.Map.Layers["vertices_tmp"]);
  608. // Create image.
  609. Image newImage = Image.FromFile(@"D:\Past Desktop\GeoHyperstar(for RSA)\GeoHyperstar\Ball_blue.png");
  610. if(intersection!=null)
  611. SharpMap.Rendering.VectorRenderer.DrawMultiPoint(g, intersection, newImage, 0.1f, new PointF(0,0), 0, mapImage1.Map);
  612. ////?????
  613. //if(intersection!=null)
  614. // intersection.Render(g, mapImage1.Map);
  615. RenderElementByID(Convert.ToInt16(NodeInput_tb.Text.Trim()), Color.Red, "Point", false, g);
  616. }
  617. //???????ID????????????
  618. private void NodeInput_tb_KeyDown(object sender, KeyEventArgs e)
  619. {
  620. if (e.KeyCode == Keys.Return)
  621. FindElement_btn.PerformClick();
  622. }
  623. #region ??????
  624. //????????????
  625. private SharpMap.Styles.VectorStyle GetRoadStyle(SharpMap.Data.FeatureDataRow row)
  626. {
  627. SharpMap.Styles.VectorStyle style = new SharpMap.Styles.VectorStyle();
  628. int x = int.Parse(row["ID"].ToString());
  629. if (x <= 500)
  630. {
  631. style.Fill = Brushes.Green;
  632. return style;
  633. }
  634. else if (x <= 1000)
  635. {
  636. style.Fill = Brushes.Blue;
  637. style.Outline = Pens.Red;
  638. return style;
  639. }
  640. else
  641. {
  642. style.Fill = Brushes.Red;
  643. return style;
  644. }
  645. }
  646. //?????????????,?????????????????????sharpmap??????
  647. //?MinVisibility?MaxVisibility
  648. //??????????????????????????????????????????
  649. /*
  650. * Define DS;
  651. * Foreach (Layer i as VectorLayer in Map.Layers)
  652. * {
  653. * i.ExecuteIntersects(Envelope,DS)
  654. * }
  655. *
  656. *
  657. */
  658. private SharpMap.Map ClassifiedRoadMap(SharpMap.Layers.Layer _mylyr, SharpMap.Map m)
  659. {
  660. VectorLayer[] ClassifiedLayer=new VectorLayer[8];
  661. VectorLayer query_lyr = _mylyr as VectorLayer;
  662. if (!query_lyr.DataSource.IsOpen) query_lyr.DataSource.Open();
  663. //get all the features in the query_lyr.
  664. SharpMap.Data.FeatureDataSet ds = new SharpMap.Data.FeatureDataSet();
  665. query_lyr.DataSource.ExecuteIntersectionQuery(query_lyr.Envelope, ds);
  666. query_lyr.DataSource.Close();
  667. if (ds == null) return null;
  668. Collection<SharpMap.Geometries.Geometry>[] GeomCols = new Collection<SharpMap.Geometries.Geometry>[8];
  669. for (int i = 1; i <= 8; i++)
  670. {
  671. GeomCols[i - 1] = new Collection<SharpMap.Geometries.Geometry>();
  672. if(i!=8)
  673. {
  674. ClassifiedLayer[i - 1] = new VectorLayer("roadkind_"+i.ToString());
  675. foreach(FeatureDataRow j in ds.Tables[0].Rows)
  676. {
  677. if (Convert.ToInt16(j["roadkind"]) == i)
  678. {
  679. GeomCols[i-1].Add(j.Geometry);
  680. }
  681. }
  682. }
  683. else
  684. {
  685. ClassifiedLayer[i - 1] = new VectorLayer("roadkind_9");
  686. foreach (FeatureDataRow j in ds.Tables[0].Rows)
  687. {
  688. if (Convert.ToInt16(j["roadkind"]) == 9)
  689. {
  690. GeomCols[i - 1].Add(j.Geometry);
  691. }
  692. }
  693. }
  694. ClassifiedLayer[i - 1].DataSource = new SharpMap.Data.Providers.GeometryFeatureProvider(GeomCols[i-1]);
  695. ClassifiedLayer[i - 1].Style.Line = new System.Drawing.Pen(System.Drawing.Color.LightBlue, 1);
  696. ClassifiedLayer[i - 1].SRID = 2450;
  697. }
  698. for (int i = 1; i <= 8;i++ )
  699. {
  700. //??roadkind_9???????????????ZoomtoExtent?????1/5??????5??????
  701. if(i==8)
  702. ClassifiedLayer[i-1].MaxVisible = fullzoom * 1 / 5;
  703. }
  704. m.Layers.Clear();
  705. foreach (var i in ClassifiedLayer)
  706. {
  707. m.Layers.Add(i);
  708. }
  709. return m;
  710. }
  711. #endregion
  712. //????roadkind????road??
  713. private void testToolStripMenuItem_Click(object sender, EventArgs e)
  714. {
  715. ClassifiedRoadMap(mapImage1.Map.Layers["road"] as VectorLayer, mapImage1.Map);
  716. mapImage1.Map.ZoomToExtents();
  717. mapImage1.Refresh();
  718. }
  719. //??????
  720. private void SetColr_Click(object sender, EventArgs e)
  721. {
  722. string lyr_name = Layers_clb.SelectedItem.ToString();
  723. var selctedlyr = this.mapImage1.Map.GetLayerByName(lyr_name) as SharpMap.Layers.VectorLayer;
  724. colorDialog1.ShowDialog(this);
  725. selctedlyr.Style.Line.Color = colorDialog1.Color;
  726. mapImage1.Refresh();
  727. }
  728. //??????????Map
  729. private void mapContext_refresh_Click(object sender, EventArgs e)
  730. {
  731. if (mapImage1.Map != null)
  732. {
  733. HashSet<string> Enabled = new HashSet<string>();
  734. for (int i = 0; i < Layers_clb.CheckedIndices.Count; i++)
  735. {
  736. string lyrname = Layers_clb.Items[Layers_clb.CheckedIndices[i]].ToString();
  737. Enabled.Add(lyrname);
  738. }
  739. foreach (var lyr in mapImage1.Map.Layers)
  740. {
  741. if (!Enabled.Contains(lyr.LayerName))
  742. lyr.Enabled = false;
  743. else lyr.Enabled = true;
  744. }
  745. mapImage1.Refresh();
  746. }
  747. else { MessageBox.Show(this, "No layers in map,please add the layers first", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); }
  748. }
  749. private void Layers_clb_MouseDown(object sender, MouseEventArgs e)
  750. {
  751. if (e.Button == MouseButtons.Right)
  752. {
  753. for (int i = 0; i < Layers_clb.Items.Count; i++)
  754. {
  755. Rectangle ItemRect = Layers_clb.GetItemRectangle(i);
  756. if (ItemRect.Contains(new Point(e.X, e.Y)))
  757. {
  758. Layers_clb.SelectedItem = Layers_clb.Items[i];
  759. Layers_clb.ContextMenuStrip = setStyleContext;
  760. break;
  761. }
  762. else
  763. Layers_clb.ContextMenuStrip = null;
  764. }
  765. }
  766. }
  767. private void zoomToLayerToolStripMenuItem_Click(object sender, EventArgs e)
  768. {
  769. string lyr_name = Layers_clb.SelectedItem.ToString();
  770. var selctedlyr = this.mapImage1.Map.GetLayerByName(lyr_name) as SharpMap.Layers.VectorLayer;
  771. mapImage1.Map.ZoomToBox(selctedlyr.Envelope);
  772. mapImage1.Refresh();
  773. }
  774. private void zoomToExtentToolStripMenuItem_Click(object sender, EventArgs e)
  775. {
  776. mapImage1.Map.ZoomToExtents();
  777. mapImage1.Refresh();
  778. }
  779. private void googleEarthItToolStripMenuItem_Click(object sender, EventArgs e)
  780. {
  781. List<string> Enabled = new List<string>();
  782. foreach (var lyr in mapImage1.Map.Layers)
  783. {
  784. if (lyr.Enabled)
  785. {
  786. Enabled.Add(lyr.LayerName);
  787. }
  788. }
  789. string path = @"D:\mymap.kml";
  790. GoogleEarthKML kml = new GoogleEarthKML(ConnStr, Enabled.ToArray(), path);
  791. kml.WriteKMLFile();
  792. ProcessStartInfo psInfNotepad = new ProcessStartInfo("notepad.exe", path);
  793. Process.Start(psInfNotepad);
  794. ProcessStartInfo psInfGE = new ProcessStartInfo(@"C:\Program Files\Google\Google Earth\client\googleearth.exe", path);
  795. Process.Start(psInfGE);
  796. }
  797. //??????????????????????????????????
  798. private void Map_MouseEnterEventHandler(object sender, EventArgs e)
  799. {
  800. int count=0;
  801. foreach (var lyr in mapImage1.Map.Layers)
  802. {
  803. if(lyr.Enabled)count++;
  804. }
  805. if (count == 0) mapImage1.ContextMenu = null;
  806. else mapImage1.ContextMenuStrip = mapContext;
  807. }
  808. private void RenderScanned_btn_Click(object sender, EventArgs e)
  809. {
  810. HashSet<int> GIDs = new HashSet<int>();
  811. //using (StreamReader sr = new StreamReader("..\\..\\NDHEU_scanned.txt"))
  812. using (StreamReader sr = new StreamReader("..\\..\\ScannedNodes.txt"))
  813. {
  814. while (sr.Peek() > 0)
  815. {
  816. int i = int.Parse(sr.ReadLine());
  817. GIDs.Add(i);
  818. }
  819. }
  820. foreach (int i in GIDs)
  821. {
  822. RenderElementByID(i, Color.FromArgb(120, 0, 0, 167), "Point", false, g);//?????????0,0,167
  823. }
  824. }
  825. private void RenderScannedLinks_btn_Click(object sender, EventArgs e)
  826. {
  827. HashSet<int> GIDs = new HashSet<int>();
  828. using (StreamReader sr = new StreamReader("..\\..\\ScannedLinks.txt"))
  829. {
  830. while (sr.Peek() > 0)
  831. {
  832. int i = int.Parse(sr.ReadLine());
  833. GIDs.Add(i);
  834. }
  835. }
  836. foreach (int i in GIDs)
  837. {
  838. RenderElementByID(i, Color.FromArgb(120, 0, 0, 167), "PolyLine", false, g);//?????????0,0,167
  839. }
  840. }
  841. private void SaveImage_btn_Click(object sender, EventArgs e)
  842. {
  843. SaveFileDialog sfd=new SaveFileDialog();
  844. sfd.InitialDirectory = Path.GetFullPath("..\\..\\");
  845. //sfd.Filter = "emf file|*.emf";
  846. sfd.Title = "Save picture";
  847. if (sfd.ShowDialog()==DialogResult.OK)
  848. {
  849. using (FileStream fs = new FileStream(sfd.FileName, FileMode.OpenOrCreate))
  850. {
  851. Metafile mf = mapImage1.Map.GetMapAsMetafile();
  852. mf.Save(fs,ImageFormat.Tiff);
  853. }
  854. }
  855. }
  856. }
  857. }