上一篇介绍了在GMap上添加自定义标签(GMapMarker),这篇介绍在GMap上添加多边形(GMapPolyogn),并且介绍如何在地图上画任意的多边形。
如果已经知道了多边形的各个点的位置,就可以通过如下方式在地图上添加多边形:
GMapOverlay polyOverlay = new GMapOverlay("polygons"); List points = new List(); points.Add(new PointLatLng(-25.969562,32.585789)); points.Add(new PointLatLng(-25.966205,32.588171)); points.Add(new PointLatLng(-25.968134,32.591647)); points.Add(new PointLatLng(-25.971684,32.589759)); GMapPolygon polygon = new GMapPolygon(points, "mypolygon"); polygon.Fill = new SolidBrush(Color.FromArgb(50, Color.Red)); polygon.Stroke = new Pen(Color.Red, 1); polyOverlay.Polygons.Add(polygon); gmap.Overlays.Add(polyOverlay);
如果需要手动在地图上画多边形,可以通过在地图上记录每个点击的位置,每次点击更新正在画的多边形就可以了,实现方式如下:
先定义一些变量:
private GMapOverlay polygons = new GMapOverlay("polygon"); //放置polygon的图层 private GMapPolygon drawingPolygon = null; //正在画的polygon private List<PointLatLng> drawingPoints = new List<PointLatLng>(); //多边形的点集 private GMapPolygon currentPolygon;
mapControl.Overlays.add(polygons);
在点击mousedown事件中更新多边形的点集(即更新多边形的形状):
void mapControl_MouseDown(object sender, MouseEventArgs e) { if (e.Button == System.Windows.Forms.MouseButtons.Left) { isLeftButtonDown = true; if (checkBoxDrawPolygon.Checked) { drawingPoints.Add(mapControl.FromLocalToLatLng(e.X, e.Y)); if (drawingPolygon == null) { drawingPolygon = new GMapPolygon(drawingPoints, "my polygon"); drawingPolygon.Fill = new SolidBrush(Color.FromArgb(50, Color.Red)); drawingPolygon.Stroke = new Pen(Color.Blue, 2); drawingPolygon.IsHitTestVisible = true; polygons.Polygons.Add(drawingPolygon); } else { drawingPolygon.Points.Clear(); drawingPolygon.Points.AddRange(drawingPoints); if (polygons.Polygons.Count == 0) { polygons.Polygons.Add(drawingPolygon); } else { mapControl.UpdatePolygonLocalPosition(drawingPolygon); } } //mapControl.Refresh(); } } }
在双击事件中将当前正在画的多边形加到保存多边形的GMapOverlay中:
void mapControl_MouseDoubleClick(object sender, MouseEventArgs e) { if (checkBoxDrawPolygon.Checked && drawingPolygon != null) { polygons.Polygons.Add(drawingPolygon); drawingPolygon = null; drawingPoints.Clear(); } }
在OnPolygonEnter和OnPolygonLeave中改变多边形的轮廓颜色:
void mapControl_OnPolygonLeave(GMapPolygon item) { currentPolygon = null; item.Stroke.Color = Color.MidnightBlue; } void mapControl_OnPolygonEnter(GMapPolygon item) { currentPolygon = item; item.Stroke.Color = Color.Red; }
采用同样的方法,可以在地图上画矩形、圆形等图形,画矩形和圆形的时候要随鼠标移动改变图形的大小,需要在MouseMove事件中改变正在画的图形的大小。
由于圆形没法用点集组成(无穷个点组成),可以采用GMapMarker来画。
效果图如下: