Continuing from the previous GMap.NET Tutorial – Maps, markers and polygons on this site, this article shows how you can show a route on your map. It is assumed that you know how to setup a GMap.NET project, and set your map to your desired location (if not, read through the other tutorial first). Like […]

This article was posted by Independent Software, a website and database application development company based in Maputo, Mozambique. Our website offers regular write-ups on technical and design issues, ranging from details at code level to 3D Studio Max rendering. Read more about Independent Software's philosophy, or get in touch with Independent Software.

Continuing from the previous GMap.NET Tutorial – Maps, markers and polygons on this site, this article shows how you can show a route on your map. It is assumed that you know how to setup a GMap.NET project, and set your map to your desired location (if not, read through the other tutorial first).

Like the maps themselves, routes are provider-specific. GMap.NET can use a whole slew of providers, but typically (for me at least) Google Maps seems to have the best data. When you want to show a route from point A to point B, the mapping provider will calculate the best route, using flags like “avoid highways” or “walking route”. Mapping providers with better data will provide better routes. When a mapping provider has little data on the area you’re showing, your route is likely going to be “as the crow flies”, since garbage in = garbage out.

Specifying the route

You can specify a route in two ways: by providing a starting and ending latitude/longitude pair, or by providing a string of text describing the start and end points. With a good mapping provider, the string will work. If the mapping provider has little knowledge of the area, you’re better off providing coordinate pairs, but it’s likely the route calculating will be bad as well.

So, in order to create a route, either do:

or

You’ll notice that the map provider (Google, in this case) provides the GetRoute method that we need to create a MapRoute instance. You could use a different mapping provider (BingMapProvider, for instance) to create the route, and use it with yet another provider for the actual map images. After all, it all boils down to latitude/longitude coordinates.

Apart from the start and end points, the GetRoute method takes some more arguments. The two boolean flags are:

  • avoidHighways – If set, the mapping provider will try to avoid highways, instead taking the scenic route (if supported);
  • walkingMode – If set, the mapping provider will assume that you’re going on foot and include footpaths (if supported).

Finally, the last argument is the zoom mode. This is the zooming level at which the route will be calculated. Higher zoom modes yield better results. If you put in a low zoom mode, chances are your route will cut through buildings. A zoom mode of 15 has worked well for me.

Adding the route to the map

Now the MapRoute instance has been created, but it won’t show yet. We’ll need to do two more things: wrap the route up in a GMapRoute instance so that it can be named and shown, and then added it to an overlay. This neatly follows how everything else works in GMap.NET: everything goes into an overlay. So the first thing to check is something doesn’t show up is always, “Did I forget to add it to my overlay?”

The GMapRoute constructor takes a set of points. This means that although we had our mapping provider calculate the points for us, we could stick in a list of points ourselves, as well. Let’s add the GMapRoute instance to an overlay now, and add the overlay to our map:

The result should be:

Adding a route to GMap.NET

Adding a route to GMap.NET

Styling the route

By default, a route is drawn using a fat, semitransparent blue line. This can be changed. The GMapRoute class provides a Stroke member that is an instance of Pen. Beware: do not create a new instance of Pen and assign it to the Stroke member, as this will create a memory leak. Instead, assign the Pen attributes directly like so:

Happy GMap.NET developing!

Trackbacks

  1. GMap.NET Tutorial – Maps, markers and polygons | Websofia
  2. GMap.NET Tutorial – Maps, markers and polygons | Ivanchoboy's Blog
  3. GMap.NET Tutorial – Maps, markers and polygons | Independent Software

Comments

66 66 Responses to “GMap.NET Tutorial – Routes”
  1. Marty says:

    How do I add intermediate points to the Route ?

  2. cellurl says:

    Nice clean description. Side question: How current are tweets below? I want to add them to my site, but I don’t understand if they “cycle” thru old tweets. Yours seems to move a lot and I can’t believe you have that much going on at any given minute. Thanks for posting tutorial.

  3. Rodrigo says:

    Hi Alex, I can’t handle routes on my WPF app.
    There’s no GMapRoute class on my referenced dlls.

    I’m using something like this:
    MapRoute route = GMap.NET.MapProviders.GoogleMapProvider.Instance.GetRouteBetweenPoints(points[0], points[1], false, false, 15);

    but now I cannot add it to my MapControl.
    And there’s no overlays too.
    I’m a little bit lost here, can you please help me through this?
    Just wanna show the route between two points.

    • alex says:

      If there’s no GMapRoute class available, you must be using a different version of GMap.NET. Make sure you’re all updated, and then see if it’s not there. Use the class browser in Visual Studio.NET to find out there the class is – possible it has been renamed in newer versions, which is another possibility.

      • 陈紫皖 says:

        hi,thank you ,i am a chinese boy, but i have some questions
        i’m using something like this:
        MapRoute route = GMap.NET.MapProviders.GoogleMapProvider.Instance.GetRouteBetweenPoints(points[0], points[1], false, false, 15);
        but it return null, i’m a little lost, can you help me ,thank you!

        • GojiraSama says:

          I had to use OpenStreet or something else. I don’t think Google or Bing are allowing routes. I get nulls on both.

  4. Franklin says:

    Hey! The Overlay does not get displayed at all. When I debug, it stops just after the add.overlay

  5. Roy says:

    Hi Alex!
    Is it possible to make the routes draggble?

  6. Sergey says:

    Hi, Alex! How to learn the direction of movement on the route. For a example: if the car has drives in the both directions. How to set “arrays”?

  7. Sergey says:

    How to set “arrows”?

  8. dave says:

    like all my friends here i I can’t handle routes ????????????
    please give us answers !!!!!!!!!!

  9. dave says:

    like all my friends here i I can’t handle routes ????????????
    please give us answers !!!!!!!!!!

    • alex says:

      Hello Dave – can you be more specific? What is the problem?

      • dave says:

        hi alex thanks a lot for your response

        when i use this
        Dim route As MapRoute = GMap.NET.MapProviders.GoogleMapProvider.Instance.GetRouteBetweenPoints(start, endStop, False, False, 13)
        in route there is nothing
        i see in forums that radioman use getroute but it doesn t exist in the instance property

        a second questions how can i change the language of the google map now it is in english
        i need it in the local language

        • Toastbrot says:

          the method name got recently to “GetRouteBetweenPoints()”. please just look trough the class bevore you ask…

  10. dave says:

    hi alex thanks a lot for your response

    when i use this
    Dim route As MapRoute = GMap.NET.MapProviders.GoogleMapProvider.Instance.GetRouteBetweenPoints(start, endStop, False, False, 13)
    in route there is nothing
    i see in forums that radioman use getroute but it doesn t exist in the instance property

    a second questions how can i change the language of the google map now it is in english
    i need it in the local language

  11. charl says:

    MapRoute route = GMap.NET.MapProviders.GoogleMapProvider.Instance.GetRoute(start, end, false, false, 15);

    what is the error if the GetRoute is the problem?

  12. kiran says:

    i want to calculate the latitude and langetude while giving the address plese give me the code in c#

  13. Maul says:

    i currently working for my boat tracking. but when i use this maps i can’t make routes on sea. can you tell me how to make raw line on the maps based on latitude and longitude

  14. Phạm Tuấn Anh says:

    Hi, Alex! Can you help me about geocoding in Gmap.net? Please! Help me. I need you feedback soon

  15. Ravan says:

    Hi Alex,

    Very good tutorial.
    Can you tell me how to draw the polygon on the map and find x and y coordinate within this.

    Thanks

  16. Mark says:

    It would be good to mention in the article that you can define your own route by adding a series of PointLatLng. In other words, for just drawing any desired lines on the map!

    • lu8890 says:

      hi Mark, what you mentioned is exactly what I am looking to do on my project.
      If it’s not too much trouble, do you mind provide some pointers on how to accomplish this?

      thanks!

  17. Achim says:

    Hi,
    is it possible anyway to use routing offline ?

    • Florian says:

      Yes, you can preload the Mapdata of an specefic Area to your Cache. After that, you can use the Preload-Sector offline. Check radioman’s demo out, there’s an preload function. I use it too and it’s works fine with my programm 😀

  18. mustafa says:

    Hi,
    Could you tell me that how I could get route coordinate array from route.
    Thank you

  19. Willian says:

    Hi, I have a question!
    So, I wanna create many routes and each route with your own color. someone how know I make it?

    I tried to create each route with own overlay and after change the color of route, but when I change the color of one, all routes change too! :(
    Same those that stay in diferent overlays!

    Thanks!

    Congratulations by project!

    • Afshin says:

      Hi William,
      did you find any solution for this problem? I have the same issue..

      cheers,
      Afshin

    • pendragon says:

      I have the same worries, this is due to the method OnRender of GmapOverlays, it makes a foreach, so all routes are affecteds by the color defines by us, one can therefore not with this version of DDL make several routes with different colors.
      At least I haven’t found how to do, wait a future release I think

      But it’s a great work, so fun
      Congrats

      • pendragon says:

        I found the solution to have different colored routes for each of them, use it before adding a Overlays

        r.Stroke = new Pen(GMapRoute.DefaultStroke.Brush);
        r.Stroke.Width = WidthRoute;
        r.Stroke.Color = Color.Orange;

        If you use symply the demo code :

        r.Stroke.Width = 2;
        r.Stroke.Color = Color.SeaGreen;
        All routes are the same Color ans Width, logical :)
        Enjoy

    • Vladimir says:

      here how you can resolve this problem
      http://stackoverflow.com/questions/26989923/gmap-net-route-multi-color

      code:
      route.Stroke= (Pen)route.Stroke.Clone();
      route.Stroke.Color = Color.Orange;

  20. Jhon says:

    Hello Alex, thanks for the tutorial ! I have few issue with the latest version and it seem the syntax doesn’t match with yours, so can you provide us the same version used when you wrote this tutorial? I can hardly found any tutorial or documentation to help me out… I really need help for my school project.

  21. Galbas says:

    Hello!
    Is it possible to read a static map in dwg or bmp format?
    Thanks.

  22. Eduardo says:

    Hi great work!. Is possible insert a marker animated?; for example a pulsing marker? in NET

  23. Arafii says:

    Is there a way to add a route for live data? Meaning there’s no end location, but the route updates with live GPS data?

  24. Meindert says:

    Hi alex, how can I check whether the mouse moves over a route…and then I want to show some information concerning that route…

  25. dean says:

    Hi

    As of today we’re experiencing adhoc failures when calling GMaps.Instance.GetRouteBetweenPoints. The call is returning null, The problem occurs in version 1 & 1.5.4.3 of the Core and WindowsForms.
    We’re using this overload PointLatLng start, PointLatLng end, bool avoidHighways, int Zoom, with these params –
    50.966122,0.254626, 50.89757,0.07477, false, 0)

    We know the lats and longs are good.

    To reiterate, we are experiencing a vast level of failure when calling GetRouteBetweenPoints. We have been using this for years.

    Many thanks

    • Ashi says:

      We’re getting the same problem when using the GetRouteBetweenPoints method.

      Any solution or workaround would be welcomed!

      Thanks!

    • Nelson says:

      Please are there any alternatives to getting the accurate route between two points?

    • Nelson says:

      when I instantiate route:
      MapRoute route = GMap.NET.MapProviders.GoogleMapProvider.Instance.GetRoute(start, end, false, false, 15);
      and call route.Distance, I always get an error, because route is null. Please is there any alternative. I really need this. Thanks

      • Ashi says:

        Since the GetRouteBetweenPoints between point seems to return null, I’ve added the following code to do manually create an areal route (as the crew fly) if no route is returned:

        route = GoogleMapProvider.Instance.GetRouteBetweenPoints(start, end, false, false, 15);
        if (route == null)
        {
        List lstPoints = new List {start ,end};
        route = new MapRoute (lstPoints,”Route” + i.ToString ());
        }

  26. BOIS says:

    Hello,
    I have the same problem , when calling GMaps.Instance.GetRoute The call is returning null,
    We’re using this overload (PointLatLng start, PointLatLng end, bool avoidHighways,bool walking mode, int Zoom)
    with these params ( PointLatLngstart( 6,973888874054 47,87194442749 ),PointLatLng end( 6,973888874054 47,87194442749) , false , false , 0)
    The lats and longs are good.

    private double CalculDistance(PointLatLng start, PointLatLng end)
    {
    GMapProvider.WebProxy = WebRequest.GetSystemWebProxy();
    GMapProvider.WebProxy.Credentials = CredentialCache.DefaultCredentials;
    GMap.NET.GMaps.Instance.Mode = GMap.NET.AccessMode.ServerOnly;
    MapRoute route = GMap.NET.MapProviders.GoogleMapProvider.Instance.GetRoute(start, end, true, false, 0);

    returns route.Distance
    }

    I have Gmap.NET.Core.dll et Gmap.NET.WindowsForm.dll at version 1.7.0.0

    Since June 29, 2015, the function returns null, while it works for 1 or 2 years
    Do you have a track or an index to help me.
    Thank you in advance for your comments.

    • Meindert says:

      I’m having the same issue…GetRoute gives a route that is NULL…so the application crashes constantly :(

      • Vinicius says:

        GDirections ss;
        var xx = GMapProviders.GoogleMap.GetDirections(out ss, start, end, false, false, false, false, false);
        GMapRoute r = new GMapRoute(ss.Route, “My route”);

        try this….

  27. Meindert says:

    Is it possible to select a whole street by using the GMapRoute object? Or is there another way to do that?

  28. Javier says:

    Well, If you use GoogleMapProvider, you’ll get null in this:

    MapRoute route = GMap.NET.MapProviders.GoogleMapProvider.Instance.GetRoute(start, end, false, false, 15);

    But! I’m using another provider; OpenStreetMap, and it works perfectly. so it’s like this:

    MapRoute route = GMap.NET.MapProviders.OpenStreetMapProvider.Instance.GetRoute(start, end, false, false, 15);

  29. Hari says:

    Hi,
    Thank you for this great library.
    There is the possibility to calculate the travel time?

    Thanks for your help.
    Hari.

  30. jalal says:

    hi,
    i have one problem in gmap . please i need to solve it .
    i want to get directions duration in the gmap and save it in database for personal use .
    how i can to do this ?

  31. AHtesham Ur Rahim says:

    how to display polygon or the route on the map.. even if it exits or not. please reply me as soon as possible.
    here is the code.
    GMapOverlay polyoverlay = new GMapOverlay(“Polygons”);
    List points = new List();
    points.Add(new PointLatLng(33.578989, 73.064408 ));
    points.Add(new PointLatLng(33.57905, 73.064372));
    points.Add(new PointLatLng(33.578855, 73.064433));
    points.Add(new PointLatLng(33.578877, 73.064572));
    points.Add(new PointLatLng(33.578413, 73.06473));
    points.Add(new PointLatLng(33.578291, 73.064663));
    GMapPolygon polygon = new GMapPolygon(points, “mypolygon”);
    polygon.Fill = new SolidBrush(Color.FromArgb(50, Color.LightGreen));
    polygon.Stroke = new Pen(Color.Green, 1);
    polyoverlay.Polygons.Add(polygon);
    gMapControl1.Overlays.Add(polyoverlay);

    when i run the code there is nothing to display… please help me out..
    Thanks in advance

  32. Sharon says:

    Hi,

    This is a great solution, love it.

    I have two problems.
    The route I am getting is not as optimized as the one I can see on Bing or Google, I was trying both map provider MapRoute route = GMap.NET.MapProviders.BingMapProvider.Instance.GetRoute(Start, End, false, false, 22); but not getting a good route.

    Second issue, how do I zoom the map so the route will be in a full view without the need of the user to zoom in and out after the routing is completed.

    Your help is greatly appreciated.

    Sharon

  33. Alvaro says:

    MapRoute me retorna null, luego prosegui a cambiar de proveedor ahora ejecuta normal mi codigo pero no muestra la ruta

  34. vamsi says:

    string start = “Avenida Armando Tivane, Maputo, Mozambique”;
    string end = “Rua 1301, Maputo, Mozambique”;
    MapRoute route = GMap.NET.MapProviders.GoogleMapProvider.Instance.GetRoute(start, end, false, false, 15);

    as i am running this , i has null value in route and i am getting error even if change the map provider to openstreetmapprovider.

    please help me..needed it urgent. thanks in advance

  35. Meysam says:

    I create a rout:

    PointLatLng start = new PointLatLng(34.633440, 50.867821);
    PointLatLng end = new PointLatLng(34.618707, 50.844945);
    MapRoute route = GMap.NET.MapProviders.GoogleMapProvider.Instance.GetRoute(
    start, end, false, false, 15);

    But Overlay word does not known, that I my route to it. did I miss a references?

  36. Emilio J says:

    Hi, How can I add point to polygon added to Overlays?


    GMapOverlay polyOverlay = new GMapOverlay(“polygons”);
    IList 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);

    //When I press a button I want to add a point to “mypolygon” ¿how can I do?

    Thank you.

    Regards,
    Emilio.

  37. Iuri Braga says:

    is it possible to animate a marker across the route? I’ve tried using a timer but I can’t get it working… Does this API suport this? Or will I need to use something else( like LiveMaps from Microsoft?? ) HELP

  38. valasidis vasileios says:

    Is it possible to have bounded or multimap horizontally ?

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">