Pages - Menu

2020年9月5日 星期六

[c#]Gmap.net For winform

前言

要在WinForm上面使用地圖,本來還想說乾脆直接丟網址讓人點就好,

最後發現這個套件,GMap.NET,其實也有找到另一套MapWinGIS

看起來也都是可以在WinForm上面執行的。

 

正文

首先去nuget下載套件 GMap.NET.WinForms,過程就不多說了。

然後在工具箱那邊會看到控制項,剛要重新找控制項,卻發現他消失了!?

WTF,那我當初怎麼拉過來的阿阿阿…記得很清楚,一開始不知道怎麼寫的時候,

這個是突然出現在我工具箱上面的…

現在突然消失!!!太神奇了

如果真的沒有在工具箱上面,現在想到的方法只有開啟舊的專案,把控制項複製過去。

剛剛又看了一篇trying to add Gmap.Net control to toolbox,這個可以試試。

這篇是在說要順便裝WindowsPresentation.dll的引用(這個要去nuget裡面抓GMap.NET.WinPresentation (Fig.1)),

雖然我剛裝了沒用,但關掉後重開就出現了(Fig.2)。

 

簡單使用的方式,

MainMap是控制項ID

 

使用座標來指定預設位置,並可設定縮放大小

 

MainMap.Position = new PointLatLng(54.6961334816182, 25.2985095977783);
MainMap.MinZoom = 0;
MainMap.MaxZoom = 24;
MainMap.Zoom = 17;


MainMap.ScaleMode = ScaleModes.Fractional;

//----------------------------------------
// Custom Layers   增加圖層
//----------------------------------------
MainMap.Overlays.Add(Routes);
MainMap.Overlays.Add(Polygons);
MainMap.Overlays.Add(Objects);
MainMap.Overlays.Add(_top);

 

之後所有的動作,都是在圖層上面操作的。

再來是增加標記點,目前也只打算做到這。

呼叫方式

AddLcation(32.0689660, 110.3952002);

 

void AddLcation(double lat,double lng)
{
    PointLatLng addPoint = new PointLatLng(lat, lng);
    // set current marker
    GMapMarker addMarker = new GMarkerGoogle(addPoint, GMarkerGoogleType.red_dot);
    addMarker.IsHitTestVisible = false;
    _top.Markers.Add(addMarker);
}

 

再來的事件是,當我點下去的時候,能夠得知目前的座標。

void MainMap_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        _isMouseDown = true;

        if (_currentMarker.IsVisible)
        {
             _currentMarker.Position = MainMap.FromLocalToLatLng(e.X, e.Y);

            var px = MainMap.MapProvider.Projection.FromLatLngToPixel(_currentMarker.Position.Lat, _currentMarker.Position.Lng, (int)MainMap.Zoom);
            var tile = MainMap.MapProvider.Projection.FromPixelToTileXY(px);
            txtLoca.Text = _currentMarker.Position.ToString();
        }
    }
}

有很多的code是從GMap.Net Github抄出來的 只是稍微小小的修改。

 

ref.

GMap.NET 使用教程【1】

C#專案之 GMap.net 標記點及 繪製多點之間的距離

沒有留言:

張貼留言