GMap.NET Tutorial – Maps, markers and polygons

GMap.NETGMap.NET LogoThe following is a tutorial for using the excellent GMap.NET control. This text will explain how to place a map control on a form, how to initialize it to show the coordinates you want, how to add markers to it, and how to add polygons.

Download the GMap.NET library here (the so-called “hot build” from 2013 – the latest stable release is from 2011 and had some problems for me).
(Note that I have another tutorial up on how to add routes to GMap.NET).

Setting up

First, create a new C# Windows Forms project in Visual Studio 2010. In your GMap.NET download, you will find DLLs named GMap.NET.Core.dll and GMap.NET.WindowsForms.dll. Place them in a subfolder of your project, and add a reference to both.

Adding GMap.NET references
This will allow your code to access GMap.NET’s classes. Since GMap.NET is a user control, you can add it to your Toolbox. (Of course, you could simply instantiate the GMapControl from your code without ever adding it to your Toolbox, but then you would miss out on setting the control’s properties conveniently through the Properties panel). To add the control to your Toolbox, right-click the Toolbox and select “Choose Items.”

Adding the GMap control to your Visual Studio Toolbox

You’ll find the required assemblies by clicking Browse… and selecting the GMap.NET.WindowsForms DLL. This should contain the GMapControl. Verify that there’s a check next to this control, and when you click OK, the control should be in your Toolbox and can be dragged to a form.

Adding a GMap to a Windows Form

Now add a new form (your fresh C# Windows Application should already have one) and drag the GMapControl to it. Resize it to your liking and call it “gmap” instead of the cumbersome GMapControl1. The control will display as an empty rectangle:

Adding the GMap Control to a form

With the control selected, open the Properties panel. Apart from the usual Control properties, you’ll find some GMap-specific properties there. Now things will get interesting:

Properties for the GMapControl

I’ll explain some of the properties right away:

  • CanDragMap – If true, the user can drag the map using the right mouse button. You’ll probably want to keep this set to true.
  • MarkersEnabled – If true, any markers that you defined will be shown. If not, they won’t appear. Set this to true for now. If you forget, you may pull your hair out figuring out why your markers don’t appear (I did).
  • PolygonsEnabled – Same story here.
  • ShowTileGridLines – If true, GMap.NET will show tile coordinates on the tiles. Not something for a production environment, but it may help with debugging.
  • Zoom, MinZoom, MaxZoom – The Zoom level for Google Maps is somewhere between 0 (zoomed out to global level) to 18 (zoomed in to street level). Zoom is the current zoom level (5 would be good for country level), while MinZoom and MaxZoom should be set to 0 and 18 respectively if you want users to be able to zoom in and out fully. Zooming is done with the mouse wheel.

All these are interesting switches that allow us to define how the map will be shown and interacted with, but they don’t allow us to set where the map data is coming from. As we will see, this must be done in code. Running the program now will result in a persistently blank rectangle where the map is supposed to go.

Initializing the map

Add an onLoad event to your form, and add the following code to it:

private void Form1_Load(object sender, EventArgs e)
{
  // Initialize map:
  gmap.MapProvider = GMap.NET.MapProviders.BingMapProvider.Instance;
  GMap.NET.GMaps.Instance.Mode = GMap.NET.AccessMode.ServerOnly;
  gmap.SetCurrentPositionByKeywords("Maputo, Mozambique");
}

Now run the program. A map should appear, centered on the city of Maputo, Mozambique. I’ve set the position using key words recognized by the map data provider, but you can also use latitude/longitude if you want:

gmap.Position = new PointLatLng(-25.971684,32.589759);

While running the program, you will notice that the map can be dragged with the right mouse button, and zooming is done with the mouse wheel. If these operations do not work, then check that you’ve set the GMapControl’s properties correctly in the Properties panel – you may have inadvertently turned off dragging, or fixed the zooming level.

Map Providers

The magic of the GMap.NET library is that is doesn’t merely work with Google Maps. There are other map data providers out there, and GMap.NET supports a slew of them while the gory API details are all neatly hidden away from you. In the example above, I’ve used the BingMapProvider, but other useful ones include:

  • CloudMadeMapProvider
  • GoogleMapProvider – map provider for Google Maps; there are street, satellite and hybrid variants
  • OpenCycleMapProvider
  • OpenStreetMapProvider
  • WikiMapiaMapProvider
  • YahooMapProvider

Interestingly, the Google Map provider is (for me, at least), the slowest one. The applications takes a good number of seconds to start, presumably because a connection with Google is being (slowly) made. The Bing Map provider was much faster. But, of course, the data shown will be different so it all depends on your preferences. At the very least, your map code could have fallback providers.

GMap.NET with Yahoo Provider

Yahoo provider

GMap.NET with Open Street Map provider

Open Street Map provider

GMap.NET with Google Maps provider

Google Maps provider

GMap.NET with Bing Maps provider

Bing Maps provider

The magic of GMap.NET goes further still. When we get to showing markers and polygons on a map, we’ll see that GMap.NET hides provider-specific implementation details away behind a common interface. That means that any marker and polygon code you write for GMap.NET will work with any of the providers. Awesome!

Adding markers

Markers are added in layers that are placed on top of your map, called overlays. You can place any number of markers in an overlay, then add that overlay to the map. The overlay can then be hidden en shown as necessary.

Here is a bit of code that adds an overlay called “markers” to the map, with a single marker in it:

GMapOverlay markersOverlay = new GMapOverlay("markers");
GMarkerGoogle marker = new GMarkerGoogle(new PointLatLng(-25.966688, 32.580528),
  GMarkerGoogleType.green);
markersOverlay.Markers.Add(marker);
gmap.Overlays.Add(markersOverlay);

Adding a marker to GMap.NET

A Google-type marker on a Bing Map provider

First, the overlay is created. You can give it a name (optionally), which you can use elsewhere to refer to it (or you could just keep a reference to the overlay instance). Next, an instance of GMarkerGoogle is created. It takes two arguments: a location (a PointLatLng instance) and a marker type.

The marker types are a variety of marker images normally available in the Google Maps API (big balloons in many colors, small balloons in many colors, etc.). Or, you can supply an instance of Bitmap with your own image:

GMarkerGoogle marker = new GMarkerGoogle(new PointLatLng(-25.966688, 32.580528),
  new Bitmap("c:\\images\\mymarker.png");

The marker is added to the overlay, and finally the overlay is added to the map. These markers (and the GMarkerGoogleType instances) work with any map provider!

Of course, you can create additional markers and add them to your overlay. There’s no limit, except in performance. More markers mean that performance goes down.

Adding polygons

Markers may not always cut it. Sometimes you need to delimit an area of your map. For instance, you may need to indicate where new construction will take place, or who owns which land. Polygons allow you to show just that.

The following code shows how to create another overlay, and add a four-point polygon to it.

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);

First, we create a new overlay. Next, we define a list with all the points in the polygon (this is a four-point polygon, but you can just as easily create many more points). Using these points, we create an instance ofGMapPolygon. For good measure, we tell the polygon how to draw itself using a SolidBrush (semitransparent) for the fill, and a thin red Pen for the stroke. Finally, we add the polygon to the overlay, and the overlay to the map.

Tip: don’t forget to add overlays to the map, or they won’t show up.

Adding a GMap.NET polygon

A polygon showing the area covered by Maputo’s Central Hospital

Conclusion

This tutorial should allow you to get started with GMap.NET. Here are some parting tips:

You can use different map providers. Some are faster than others. Also, some show more data than others. Depending on your location, this can make all the difference (Maputo, Mozambique is such as location – Yahoo Maps has almost no data).

When adding markers or polygons to an overlay, don’t forget to add the overlay to the map.

If your markers don’t show up, verify that you have MarkersEnabled set to True in the Properties panel for your GMapControl instance.

GMap.NET requires an internet connection to function properly. However, if no connection is available, you can still use cached information (if available) to show your maps. To do this,  do:

GMap.NET.GMaps.Instance.Mode = GMap.NET.AccessMode.CacheOnly;

Note: there’s more – see GMap.NET Tutorial – Routes to see how to show routes on your maps.

 

Fuente:

http://www.websofia.com/2013/02/gmap-net-tutorial-maps-markers-and-polygons/

Publicado el 18 noviembre, 2013 en C#. Añade a favoritos el enlace permanente. Deja un comentario.

Responder

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión / Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión / Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión / Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión / Cambiar )

Conectando a %s

A %d blogueros les gusta esto: