[GMap.Net] 如何於WinForm 中 render 地圖, Marker 及 Route

GMap.net 是一套user control 整合了不同的Map source (e.g. Google, OpenStreetMap 等). 它亦可以加入marker 及計算route 的距離等feature. 而它亦有出到WPF version, 但相對之下, 利用WinForm 的development 彈性較大, 而部份WinForm 有的event WPF 沒有(如Marker Click等), 須需熟識WPF 才可以掌握.

private GMapOverlay _markerOverlay;
private GMapOverlay _routeOverlay;

private void ReloadGMapControl()
{
    // 決定Map Provider.
    this.gMapControl.MapProvider = GMap.NET.MapProviders.OpenCycleMapProvider.Instance;
    // 決定存取模式. 可以cache 於client 上.
    GMap.NET.GMaps.Instance.Mode = GMap.NET.AccessMode.ServerOnly;
    // 決定如何Drag 地圖.
    gMapControl.DragButton = MouseButtons.Left;
    // 預設pre-load 位置, 可以用名search.
    gMapControl.SetPositionByKeywords("Hong Kong");
    // Disable 中間的紅十字.
    gMapControl.ShowCenter = false;

    // 加入route 及 marker 的Layer.
    this._markerOverlay = new GMapOverlay("markers");
    this._routeOverlay = new GMapOverlay("routes");
    gMapControl.Overlays.Add(this._markerOverlay);
    gMapControl.Overlays.Add(this._routeOverlay);
}

加入WayPoint 及Route

private void gMapControl_DoubleClick(object sender, EventArgs e)
{
    MouseEventArgs args = e as MouseEventArgs;
    if (args != null)
    {
        PointLatLng locationLatLng = gMapControl.FromLocalToLatLng(args.X, args.Y);
        GMapMarker marker = new GMarkerGoogle(locationLatLng, GMarkerGoogleType.green);
        _markerOverlay.Markers.Add(marker);

        WayPoint wayPoint = new WayPoint();
        wayPoint.Latitude = Convert.ToDecimal(locationLatLng.Lat);
        wayPoint.Longitude = Convert.ToDecimal(locationLatLng.Lng);
        wayPoints.Add(wayPoint);

        //this.dataGridWayPoints.Refresh();
        if (wayPoints.Count > 1)
        {
            GMapMarker lastMarker = this._markerOverlay.Markers[_markerOverlay.Markers.Count - 2];
            MapRoute route = GMapProviders.OpenCycleMap.GetRoute(lastMarker.Position, locationLatLng, true,
                true, Convert.ToInt32(gMapControl.Zoom));

            if (route != null)
            {
                GMapRoute mapRoute = new GMapRoute(route.Points, "A to B");
                this._routeOverlay.Routes.Add(mapRoute);
            }
        }
    }
}

 

About C.H. Ling 262 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.