如何使用C#中的GMAP.NET在地图上绘制圆形

4
我正在使用C#中的GMAP.NET。我能够在窗体上显示地图,现在我尝试通过在特定点单击鼠标,并按住左键拖动鼠标到特定位置来绘制一个圆形。一旦绘制完成,我想从中心点获得其英里半径,我相信GMAP有这个功能。我正在使用Opentstreet地图。
我无法实现这个功能。如果有任何已经使用过GMAP控件并且愿意分享可行代码的人,请分享您的经验。
谢谢。
9个回答

9
我所知道的实现此结果的唯一方法是创建一个PointLatLng点列表并将它们绘制为多边形。以下是一个示例:
private void CreateCircle(PointF point, double radius, int segments)
{

    List<PointLatLng> gpollist = new List<PointLatLng>();

    double seg = Math.PI * 2 / segments;

    for (int i = 0; i < segments; i++)
    {
        double theta = seg * i;
        double a = point.X + Math.Cos(theta) * radius;
        double b = point.Y + Math.Sin(theta) * radius;
    
        PointLatLng gpoi = new PointLatLng(a,b);

        gpollist.Add(gpoi);
     }
     GMapPolygon gpol = new GMapPolygon(gpollist, "pol");

     overlayOne.Polygons.Add(gpol);
 }

1
好的代码,谢谢。小调整:Math.CosMath.Sin,注意大小写,如果你要映射到一英里或两英里的比例尺,则半径需要非常小,如0.01。 - TonyG

6

如果您想使用与绘图类相关的典型GDI功能,可以简单地继承GMapMarker类。这样可以绘制简单的形状,如圆形,并创建自定义属性(例如,一个可以计算形状半径的英里数):

public class GMapPoint : GMap.NET.WindowsForms.GMapMarker
{
    private PointLatLng point_;
    private float size_;
    public PointLatLng Point
    {
        get
        {
            return point_;
        }
        set
        {
            point_ = value;
        }
    }
    public GMapPoint(PointLatLng p, int size)
        : base(p)
    {
        point_ = p;
        size_ = size;
    }

    public override void OnRender(Graphics g)
    {
        g.FillRectangle(Brushes.Black, LocalPosition.X, LocalPosition.Y, size_, size_); 
        //OR 
        g.DrawEllipse(Pens.Black, LocalPosition.X, LocalPosition.Y, size_, size_);
        //OR whatever you need

    }
 }

在地图上绘制点的方法如下:
        GMapOverlay points_ = new GMapOverlay("pointCollection");
        points_.Markers.Add(new GMapPoint(new PointLatLng(35.06, -106.36), 10));

        gMapControl1.Overlays.Add(points_);

(因为我有一些疑问)由于我们是从标记类继承的,因此仍然可以利用tooltiptext功能:

        GMapPoint pnt = new GMapPoint(new PointLatLng(35.06, -106.36), 10);
        pnt.Size = new Size(10,10);
        pnt.ToolTipText = "Text Here";
        pnt.ToolTipMode = MarkerTooltipMode.Always;
        points_.AddMarker(pnt);

1
很抱歉,@Manish Jain,我没有使用过WPF和Gmap的经验。总有一天我会转换过去,但我不期待那个学习曲线 :P - T James
1
@TheNewbie 很高兴能帮到你。由于你是从标记类继承的,所以你应该能够以与其他标记相同的方式添加工具提示。 - T James
1
@TheNewbie 没错,绘制位图要比原始绘图函数需要更长的时间。假设您正在使用上面提供的示例代码,您应该能够向GMapPoint添加工具提示内容,就像这样:GMapPoint p = new …; p.ToolTipMode = MarkerTooltipMode.Always; 和 m.ToolTipText = "文本"; 然后将其添加到图层中:points_.AddMarker(p); 我测试过了,看起来可以正常工作。希望这有所帮助。 - T James
1
@TheNewbie 看起来 OnMouseOver 使用标记的大小来确定光标是否在标记上方。如果您正在使用我的类作为原样,则从未在标记类中设置已知大小。除了您已有的内容之外,您还需要执行以下操作:pnt.Size = new Size(10, 10); 或者您想要的任何悬停容差大小。 - T James
1
那个运行得非常好。你太棒了。如果你不介意的话,看起来你以前用过这个,你有什么技巧可以让Gmap更加出色吗?还是你只是查看Gmaps的源代码并通过自己的方式弄清楚呢?无论如何,像你这样的人帮助我们这些新手,我们非常感谢。祝你有一个美好的一天! - The Newbie
显示剩余9条评论

5
   private void CreateCircle(Double lat, Double lon, double radius, int ColorIndex)
    {
        PointLatLng point = new PointLatLng(lat, lon);
        int segments = 1080;

        List<PointLatLng> gpollist = new List<PointLatLng>();

        for (int i = 0; i < segments; i++)
        {
            gpollist.Add(FindPointAtDistanceFrom(point, i*(Math.PI/180), radius / 1000));
        }

        GMapPolygon polygon = new GMapPolygon(gpollist, "Circle");
        switch (ColorIndex) {

            case 1:
                polygon.Fill = new SolidBrush(Color.FromArgb(80, Color.Red));
                break;
            case 2:
                polygon.Fill = new SolidBrush(Color.FromArgb(80, Color.Orange));
                break;
            case 3:
                polygon.Fill = new SolidBrush(Color.FromArgb(20, Color.Aqua));
                break;
            default:
                MessageBox.Show("No search zone found!");
                break;
        }


        polygon.Stroke = new Pen(Color.Red, 1);
        markers.Polygons.Add(polygon);
        gMapCtl.Overlays.Add(markers);
    }


    public static GMap.NET.PointLatLng FindPointAtDistanceFrom(GMap.NET.PointLatLng startPoint, double initialBearingRadians, double distanceKilometres)
    {
        const double radiusEarthKilometres = 6371.01;
        var distRatio = distanceKilometres / radiusEarthKilometres;
        var distRatioSine = Math.Sin(distRatio);
        var distRatioCosine = Math.Cos(distRatio);

        var startLatRad = DegreesToRadians(startPoint.Lat);
        var startLonRad = DegreesToRadians(startPoint.Lng);

        var startLatCos = Math.Cos(startLatRad);
        var startLatSin = Math.Sin(startLatRad);

        var endLatRads = Math.Asin((startLatSin * distRatioCosine) + (startLatCos * distRatioSine * Math.Cos(initialBearingRadians)));
        var endLonRads = startLonRad + Math.Atan2(Math.Sin(initialBearingRadians) * distRatioSine * startLatCos,distRatioCosine - startLatSin * Math.Sin(endLatRads));

        return new GMap.NET.PointLatLng(RadiansToDegrees(endLatRads), RadiansToDegrees(endLonRads));
    }

    public static double DegreesToRadians(double degrees)
    {
        const double degToRadFactor = Math.PI/180;
        return degrees * degToRadFactor;
    }

    public static double RadiansToDegrees(double radians)
    {
        const double radToDegFactor = 180/Math.PI;
        return radians * radToDegFactor;
    }



    public static double DistanceTwoPoint(double startLat, double startLong, double endLat, double endLong) {

        var startPoint = new GeoCoordinate(startLat, startLong);
        var endPoint = new GeoCoordinate(endLat, endLong);

        return startPoint.GetDistanceTo(endPoint);
    }

2

我遇到了同样的问题,进入时我拥有经度、纬度和半径,这是我的解决方案。 它完美无缺 :)

private void CreateCircle(Double lat, Double lon, double radius)
{
   PointLatLng point = new PointLatLng(lat, lon);
   int segments = 1000;

   List<PointLatLng> gpollist = new List<PointLatLng>();

   for (int i = 0; i < segments; i++)
      gpollist.Add(FindPointAtDistanceFrom(point, i, radius / 1000));

   GMapPolygon gpol = new GMapPolygon(gpollist, "pol");

   markers.Polygons.Add(gpol);
}

public static GMap.NET.PointLatLng FindPointAtDistanceFrom(GMap.NET.PointLatLng startPoint, double initialBearingRadians, double distanceKilometres)
{
   const double radiusEarthKilometres = 6371.01;
   var distRatio = distanceKilometres / radiusEarthKilometres;
   var distRatioSine = Math.Sin(distRatio);
   var distRatioCosine = Math.Cos(distRatio);

   var startLatRad = DegreesToRadians(startPoint.Lat);
   var startLonRad = DegreesToRadians(startPoint.Lng);

   var startLatCos = Math.Cos(startLatRad);
   var startLatSin = Math.Sin(startLatRad);

   var endLatRads = Math.Asin((startLatSin * distRatioCosine) + (startLatCos * distRatioSine * Math.Cos(initialBearingRadians)));

   var endLonRads = startLonRad + Math.Atan2(
                 Math.Sin(initialBearingRadians) * distRatioSine * startLatCos,
                 distRatioCosine - startLatSin * Math.Sin(endLatRads));

   return new GMap.NET.PointLatLng(RadiansToDegrees(endLatRads), RadiansToDegrees(endLonRads));
}

public static double DegreesToRadians(double degrees)
{
  const double degToRadFactor = Math.PI / 180;
  return degrees * degToRadFactor;
}

public static double RadiansToDegrees(double radians)
{
  const double radToDegFactor = 180 / Math.PI;
  return radians * radToDegFactor;
}

调用

CreateCircle(51.640980, -2.673544, 1143.899431);

谢谢!稍作更改后,我可以在 wpf 中执行相同的操作。 - user4860969

0

以下是如何在WPF地图上绘制一个带有黑色边框的红色圆形:

public class YourMapControl : GMapControl
{
   protected override void OnRender(DrawingContext drawingContext)
   {
      base.OnRender(drawingContext);

      Point center(40.730610, -73.935242);
      double radius = 0.1;

      drawingContext.DrawEllipse(Brushes.Red, Pens.Black, center, radius, radius);
   }
}

至于问题的第二部分,您可以使用以下内置的MapControl函数:

public bool DisableAltForSelection; //if true, selects area just by holding mouse and moving
public bool SelectionUseCircle; //use circle for selection
public event SelectionChange OnSelectionChange; //occurs when mouse selection is changed
public RectLatLng SelectedArea { get; set; } //returns rect with coordinates of the selected area

0
我的方法是覆盖绘制事件,然后定义一个矩形。一旦你定义了一个矩形,就可以画圆或弧形或扇形。
private void MainMap_Paint(object sender, PaintEventArgs e)
{
   drawPie(e.Graphics, 50, 22.321, 45.44498);   
 }

private void drawPie(Graphics g, int angle, double latitude, double longitude)
{
    PointLatLng pn = new PointLatLng(latitude , longitude );
    double dist = 295; // 200 km
    // define rectangle points
    PointLatLng p1 = FindPointAtDistanceFrom(pn, 315 * constants.DEGREES_TO_RADIAN, dist);
    PointLatLng p2 = FindPointAtDistanceFrom(pn, 45 * constants.DEGREES_TO_RADIAN, dist);
    PointLatLng p3 = FindPointAtDistanceFrom(pn, 135 * constants.DEGREES_TO_RADIAN, dist);
    PointLatLng p4 = FindPointAtDistanceFrom(pn, 225 * constants.DEGREES_TO_RADIAN, dist);
    GPoint dp1 = MainMap.FromLatLngToLocal(p1);
    GPoint dp2 = MainMap.FromLatLngToLocal(p2);
    GPoint dp3 = MainMap.FromLatLngToLocal(p3);
    GPoint dp4 = MainMap.FromLatLngToLocal(p4);

    RectangleF rec = new RectangleF(dp1.X, dp1.Y, dp2.X - dp1.X, dp3.Y - dp1.Y);
    SolidBrush ptlbrush = new SolidBrush(Color.Cyan);
    Pen ptlpen = new Pen(ptlbrush, 1);                        
    float direction1 = (-90 + angle - 45) % 360;
    float startAngle = direction1;
    float sweepAngle = 90;                                                                
    
    var brush = new SolidBrush(Color.FromArgb(50, 80, 0, 150));
    g.DrawPie(ptlpen, rec, startAngle, sweepAngle);
    if (angleFilledBox.Checked == true)
        g.FillPie(brush, Rectangle.Round(rec), startAngle, sweepAngle);

}

0
private void CreateCircle(PointF point, double radius, int segments)
{

List<PointLatLng> gpollist = new List<PointLatLng>();

double seg = Math.PI * 2 / segments;

int y = 0;
for (int i = 0; i < segments; i++)
{
    double theta = seg * i;
    double a = point.x + Math.cos( theta ) * radius;
    double b = point.y + Math.sin( theta ) * radius;

    PointLatLng gpoi = new PointLatLng(a,b);

    gpollist.Add(gpoi);
 }
 GMapPolygon gpol = new GMapPolygon(gpollist, "pol");

 overlayOne.Polygons.Add(gpol);
 }`enter code here`

所以公寓不会出现省略号


0
        GMapOverlay markers = new GMapOverlay("markers");
        private void CreateCircle(Double lat, Double lon, double radius, int segments)
        {
            markers.Polygons.Clear();
            PointLatLng point = new PointLatLng(lat, lon);

            List<PointLatLng> gpollist = new List<PointLatLng>();
            for (int i = 0; i < segments; i++)
                gpollist.Add(FindPointAtDistanceFrom(point, i, radius / 1000));

            List<PointLatLng> gpollistR = new List<PointLatLng>();
            List<PointLatLng> gpollistL = new List<PointLatLng>();
            foreach (var gp in gpollist)
            {
                if (gp.Lng > lon)
                {
                    gpollistR.Add(gp);
                }
                else
                {
                    gpollistL.Add(gp);
                }
            }
            gpollist.Clear();

            List<PointLatLng> gpollistRT = new List<PointLatLng>();
            List<PointLatLng> gpollistRB = new List<PointLatLng>();
            foreach (var gp in gpollistR)
            {
                if (gp.Lat > lat)
                {
                    gpollistRT.Add(gp);
                }
                else
                {
                    gpollistRB.Add(gp);
                }
            }
            gpollistRT.Sort(new LngComparer());
            gpollistRB.Sort(new Lng2Comparer());
            gpollistR.Clear();
            List<PointLatLng> gpollistLT = new List<PointLatLng>();
            List<PointLatLng> gpollistLB = new List<PointLatLng>();
            foreach (var gp in gpollistL)
            {
                if (gp.Lat > lat)
                {
                    gpollistLT.Add(gp);
                }
                else
                {
                    gpollistLB.Add(gp);
                }
            }
            //gpollistLT.Sort(new LngComparer());
            gpollistLB.Sort(new Lng2Comparer());
            gpollistLT.Sort(new LngComparer());
            gpollistL.Clear();


            gpollist.AddRange(gpollistRT);
            gpollist.AddRange(gpollistRB);
            gpollist.AddRange(gpollistLB);
            gpollist.AddRange(gpollistLT);
            GMapPolygon gpol = new GMapPolygon(gpollist, "pol");
            gpol.Stroke = new Pen(Color.Red, 1);
            markers.Polygons.Add(gpol);
        }

        public static GMap.NET.PointLatLng FindPointAtDistanceFrom(GMap.NET.PointLatLng startPoint, double initialBearingRadians, double distanceKilometres)
        {
            const double radiusEarthKilometres = 6371.01;
            var distRatio = distanceKilometres / radiusEarthKilometres;
            var distRatioSine = Math.Sin(distRatio);
            var distRatioCosine = Math.Cos(distRatio);

            var startLatRad = DegreesToRadians(startPoint.Lat);
            var startLonRad = DegreesToRadians(startPoint.Lng);

            var startLatCos = Math.Cos(startLatRad);
            var startLatSin = Math.Sin(startLatRad);

            var endLatRads = Math.Asin((startLatSin * distRatioCosine) + (startLatCos * distRatioSine * Math.Cos(initialBearingRadians)));

            var endLonRads = startLonRad + Math.Atan2(
                          Math.Sin(initialBearingRadians) * distRatioSine * startLatCos,
                          distRatioCosine - startLatSin * Math.Sin(endLatRads));

            return new GMap.NET.PointLatLng(RadiansToDegrees(endLatRads), RadiansToDegrees(endLonRads));
        }

        public static double DegreesToRadians(double degrees)
        {
            const double degToRadFactor = Math.PI / 180;
            return degrees * degToRadFactor;
        }

        public static double RadiansToDegrees(double radians)
        {
            const double radToDegFactor = 180 / Math.PI;
            return radians * radToDegFactor;
        }

以及这个类

class LngComparer : IComparer<PointLatLng>
    {
        #region IComparer Members

        public int Compare(PointLatLng x, PointLatLng y)
        {
            if (x == null || y == null)
                throw new ArgumentException("At least one argument is null");
            if (x.Lng == y.Lng)
            {
                if (x.Lat > y.Lat)
                {
                    return 1;
                }
                else if (x.Lat < y.Lat)
                {
                    return -1;
                }
                else
                {
                    return 0;
                }
            }
            if (x.Lng < y.Lng) return -1;
            return 1;
        }

        #endregion
    }
    class Lng2Comparer : IComparer<PointLatLng>
    {
        #region IComparer Members

        public int Compare(PointLatLng x, PointLatLng y)
        {
            if (x == null || y == null)
                throw new ArgumentException("At least one argument is null");
            if (x.Lng == y.Lng)
            {
                if (x.Lat > y.Lat)
                {
                    return 1;
                }
                else if (x.Lat > y.Lat)
                {
                    return -1;
                }
                else
                {
                    return 0;
                }
            }
            if (x.Lng > y.Lng) return -1;
            return 1;
        }

        #endregion
    }

0

我的代码绘制弧线并继承自GMapMarker。该弧线从点A到点B扫过,枢轴点位于C处。当点A和B重合时,将绘制一个圆。

    public class CustomArc : GMapMarker, ISerializable {
    [NonSerialized]
    public Pen pen;

    private int radius = 20;
    private int pen_width = 2;

    private float start = 0.0f;
    private float sweep = 0.0f;

    private GPoint ptA;
    private GPoint ptB;
    private GPoint ptC;
    private List<PointF> points;

    private static Logger logger = LogManager.GetCurrentClassLogger();

    public CustomArc(GPoint ptA, GPoint ptB, GPoint ptC, PointLatLng geo) : base(geo) {
        this.ptA = ptA;
        this.ptB = ptB;
        this.ptC = ptC;
        initialise();
    }

    private void initialise() {
        this.pen = new Pen(Brushes.White, this.pen_width);
        this.radius = (int)UIMaths.distance(ptC, ptA);

        this.points = new List<PointF>();

        if (ptA == ptB) {
            this.sweep = 360.0f;
        } else {
            // Calculate the radius
            this.sweep = (float)UIMaths.sweepAngleDeg(ptA, ptB, ptC);
        }
        this.start = (float)UIMaths.startAngle(ptC, ptB);
        Size = new Size(2 * radius, 2 * radius);
        Offset = new Point(-Size.Width / 2, -Size.Height / 2);

        Console.Out.WriteLine("Radius {0}, Start {1:0.0}, Sweep {2:0.0}", radius, start, sweep);
    }



    public override void OnRender(Graphics g) {
        try {
            Rectangle rect = new Rectangle(LocalPosition.X, LocalPosition.Y, Size.Width, Size.Height);
            g.DrawArc(pen, rect, start, sweep);

        } catch (ArgumentException ex) {
            logger.Error(ex.Message);
        }
    }

    public sealed override void Dispose() {
        if (pen != null) {
            pen.Dispose();
            pen = null;
        }

        base.Dispose();
    }

    #region ISerializable Members

    void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
        base.GetObjectData(info, context);
    }

    protected CustomArc(SerializationInfo info, StreamingContext context)
     : base(info, context) {
    }
    #endregion

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接