100% found this document useful (2 votes)
3K views39 pages

GMAP

This document provides a tutorial on using the GMap.NET control to create maps, markers, and polygons in .NET applications. It discusses downloading and configuring GMap.NET, creating a basic map by setting the map provider and centering the map, and customizing map properties. It also covers adding clickable markers to the map and different map providers that can be used.

Uploaded by

Carl Rodríguez
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
3K views39 pages

GMAP

This document provides a tutorial on using the GMap.NET control to create maps, markers, and polygons in .NET applications. It discusses downloading and configuring GMap.NET, creating a basic map by setting the map provider and centering the map, and customizing map properties. It also covers adding clickable markers to the map and different map providers that can be used.

Uploaded by

Carl Rodríguez
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 39

GMAP.

NET BEGINNERS TUTORIAL


MAPS MARKERS, POLYGONS AND
ROUTES
Since we published a tutorial for GMap.NET: Maps, markers and polygons back in
2013, it’s been viewed many times and GMap.NET remains a very popular .NET
component. Over the years, it’s become better and more stable and now that it’s at
stable version 1.7, it’s time to update the beginners tutorial to using the GMap.NET
control to create maps, markers and polygons in your .NET/C# application. In this fresh
three-part tutorial, you will learn how to place the GMap.NET control on a form, how to
configure it to show a map at the coordinates you want, how to add markers to a map,
and how to show polygons.

Since we published a tutorial for GMap.NET: Maps, markers and polygons back in
2013, it’s been viewed many times and GMap.NET remains a very popular .NET
component. Over the years, it’s become better and more stable and now that it’s at
stable version 1.7, it’s time to update the beginners tutorial to using the GMap.NET
control to create maps, markers and polygons in your .NET/C# application. In this fresh
three-part tutorial, you will learn how to place the GMap.NET control on a form, how to
configure it to show a map at the coordinates you want, how to add markers to a map,
and how to show polygons.

Getting GMap.NET and setting up

The first step to using GMap it to download GMap here. This will get you a .zip with
DLL files which contain the components you will need. For this tutorial, I have used the
latest stable version, which is 1.7 at the time of writing. There is also a hot build, but
that may contain some bugs that need ironing out. Once you’ve downloaded
GMap.NET, create a fresh Windows Forms project in your Visual Studio. Inside your
project, create a subfolder and place the DLLs you downloaded in it
(GMap.NET.Core.dll and GMap.NET.WindowsForms.dll).

In order to make your project use the new components, you need to create a reference to
the DLL files. To do so, right-click References in the Solution Explorer and select Add
Reference. In the dialog that pops up, use Browse to find the DLL files and create the
references:
The new references should now show up in the Solution Explorer. Although you are
now ready to create instances of the GMap.NET control through code, it’ll be easier to
add the GMap.NET control to the Toolbox so that you can drag it onto your forms. That
way, Visual Studio will do that instancing work for you. To add GMap.NET to your
Toolbox, right-click in your Toolbox and select Choose Items. In the dialog that
appears, use Browse to locate the GMap.NET.WindowsForms.dll file (the other DLL is
not required). It will appear pre-checked in the list of assemblies.

After you close the dialog, the new control will appear in your toolbox ready to be
dragged onto a form:
Creating your first map

Go ahead and drag an instance of the GMap.NET control onto a Windows form. Your
fresh Windows Forms application should already have an empty form ready for you.
The control will appear showing only a small red cross, but no map. We’ll need to do a
bit of coding for a map to actually appear. In the Properties window, you might as well
call it gmap rather than the cumbersome GMapControl1.

With the control selected, you will see that the Properties window offers a set of
GMap.NET specific properties apart from the usual control properties. These will allow
us to configure the behaviour of our map, but not its contents:
Here is what some of these properties do:

 CanDragMap – If set to true, the user can drag (pan) the map using the right mouse
button. You’ll probably want to keep this set to true.
 EmptyTileColor – This is the color GMap will use to draw tiles for which its could not
obtain any data from the map provider. This may happen when you’re showing a bit of
map at very high zoom levels and it depends on the provider. For instance, Google
maps has map tiles at the highest zoom levels for most land areas, but not so much for
open sea and the poles.
 MarkersEnabled – If set to true, GMap will show any markers you defined. It’s best to
leave this set to true for now, or you might be left wondering where your markers
went (this happened to me). The same applies for PolygonsEnabled and
RoutesEnabled.
 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 and 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.
 Bearing – This property will rotate the map by the specified number of degrees to the
left.

All this looks very promising, but there isn’t any property that we can use the configure
where the map data is coming from, only how it will be shown in the control. It turns
out that defining the map source must be done in code. Let’s write our first code by
creating an OnLoad event for our form. Do this by selecting the form, finding the Load
event in the Properties window and double-clicking it. In the code window, add this:

gmap.MapProvider = GMap.NET.MapProviders.BingMapProvider.Instance;
GMap.NET.GMaps.Instance.Mode = GMap.NET.AccessMode.ServerOnly;
gmap.SetPositionByKeywords("Paris, France");

Also, in the Properties window for the GMap.NET control, set MinZoom = 2,
MaxZoom = 18 and Zoom = 13. Zoom is originally set to 0, which will cause map
providers to send you errors because there is no data for that zoom level. Run your
project and see this:

Let’s take the code apart. There are three things that we must do to get a map to show in
the GMap.NET control:

 Configure a map provider: Set the MapProvider property to an instance of any of the
map providers supported by GMap. We’ve used Bing, but we’ll look at alternatives
shortly.
 Set the GMap working mode to use only server data: GMap can fetch data from a
server, from both a server and the local cache, or the local cache only. In this example,
we prefer to always fetch data from the server, so we set the Mode property to
GMap.NET.AccessMode.ServerOnly. Note that this applies to all instances of the
GMap control that you create in your application, and you only need to set this value
once.
 Center the map: Use the SetPositionByKeywords method to center your map
where you want it.

There are two things to note regarding centering the map. First, in older versions of
GMap.NET the required method was called SetCurrentPositionByKeywords, so be
careful if you’re using an previous version. Second, you won’t always have keywords to
center your map with, especially if you’re showing a region where there are few points
of reference. Therefore, you can also center your map by writing a coordinate straight to
the control’s Position property:

gmap.Position = new GMap.NET.PointLatLng(48.8589507, 2.2775175);

This will, once again, center your map on Paris, France. 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 GMap.NET control’s properties correctly in the Properties panel – you may have
inadvertently turned off dragging, or fixed the zooming level.

Getting rid of the little red cross in the middle of the map

By default, the GMap.NET control shows a little red cross on the map to show you
exactly where the center is. This may not be what you want (I always want to get rid of
it, anyway). There is no way to hide this red cross through the properties in the
Properties window, but you can set the relevant property in code:

gmap.ShowCenter = false;

… and it’s gone.

Map Providers

In the example above, we’ve configured GMap.NET to obtain all its data from the Bing
map provider. But the magic of GMap.NET is that we can use any one of a whole bunch
of map providers. Here is a short list of the most interesting ones:

 CloudMadeMapProvider
 GoogleMapProvider
 OpenCycleMapProvider
 OpenStreetMapProvider
 WikiMapiaMapProvider
 YahooMapProvider

Some map providers come have street, satellite and hybrid variants. 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. Here’s what the maps look like with different providers:
All of these providers provide different APIs, and that’s where GMap.NET really
shines. Whatever provider you choose, GMap provides you with a common interface
you can use to setup the map and add markers, polygons, and routes. This means that
when you switch to a new provider, you don’t need to change any of your code. In fact,
you could just build an option into your software that allows the user to select a
preferred provider!
ADDING CLICKABLE MARKERS TO
This tutorial explains how you can use the GMap.NET control for .NET Windows
Forms to put interactive maps on your forms, complete with clickable markers that can
be styled and responsive tooltips.

Don’t forget to visit the first part of the tutorial for GMap.NET: Setting up your map
first! If you’ve already seen this part of the tutorial, move on to part 3: GMap.NET:
Adding polygons and routes to your map.

Adding markers to the map

GMap.NET allows you to add as many markers as you like to your map, with icons of
your choosing (or even custom bitmaps). Adding markers is done through code and
requires the following steps:

 Create a map overlay that will contain your collection of markers.


 Create a new marker and add it to the overlay.
 Add the overlay to the map.

Anything that you ever want to place on a map (be it markers, polygons, or routes) must
live in an overlay. You can mix markers, polygons and routes all in the same overlay, or
you can add them to separate overlays. The latter approach allows you to show or hide
all markers in one go, while leaving the polygons and routes visible – but it’s up to you.
Here is the full code that creates a map and adds a single marker to it:

gmap.MapProvider =
GMap.NET.MapProviders.BingHybridMapProvider.Instance;
GMap.NET.GMaps.Instance.Mode = GMap.NET.AccessMode.ServerOnly;
gmap.SetPositionByKeywords("Paris, France");
gmap.ShowCenter = false;

GMap.NET.WindowsForms.GMapOverlay markers = new


GMap.NET.WindowsForms.GMapOverlay("markers");
GMap.NET.WindowsForms.GMapMarker marker =
new GMap.NET.WindowsForms.Markers.GMarkerGoogle(
new GMap.NET.PointLatLng(48.8617774, 2.349272),
GMap.NET.WindowsForms.Markers.GMarkerGoogleType.blue_pushpin);
markers.Markers.Add(marker);
gmap.Overlays.Add(markers);

You’ll see a lot of namespace prefixes here: GMap.NET, GMap.NET.WindowsForms and


GMap.NET.WindowsForms.Markers. We can clean actually this code up by moving
them to using statements:

using GMap.NET;
using GMap.NET.WindowsForms;
using GMap.NET.WindowsForms.Markers;
using GMap.NET.MapProviders;

Now our code becomes:


gmap.MapProvider = BingHybridMapProvider.Instance;
GMaps.Instance.Mode = AccessMode.ServerOnly;
gmap.SetPositionByKeywords("Paris, France");
gmap.ShowCenter = false;

GMapOverlay markers = new GMapOverlay("markers");


GMapMarker marker = new GMarkerGoogle(
new PointLatLng(48.8617774, 2.349272),
GMarkerGoogleType.blue_pushpin);
markers.Markers.Add(marker);
gmap.Overlays.Add(markers);

…which is much more readable.

Let’s take this code apart:

 We create a new instance of GMapOverlay with the name “markers”. Of course you
can give this overlay any name you want.
 We create a new instance of GMarkerGoogle (which is a specialization of
GMapMarker) and provide it with a location (a PointLatLng) and a marker type.
 We add the newly created marker to our overlay.
 We add the overlay to our map.

Our map now looks like this:

We’ve used GMarkerGoogle to create our map marker, but GMap.NET also offers
GMarkerCross (which is a simple red cross and allows no icon). As for the icons for the
Google-style marker, GMap.NET offers many. Type GMarkerGoogleType. in Visual
Studio – after you type the period, a list of possibilities will show up. Still, you can also
use your own bitmap:
GMapOverlay markers = new GMapOverlay("markers");
GMapMarker marker = new GMarkerGoogle(
new PointLatLng(48.8617774, 2.349272),
new Bitmap("mybitmap.jpg"));

And you’ll get something like this:

Adding tooltips to your markers

Just like Google Maps itself, GMap.NET allows you to add tooltips to the markers on
your map. This is as simple as putting text in a marker property:

marker.ToolTipText = "hello\nout there";

Note that I’ve used \n to make the text split over two lines. Tooltip text is always
centered in the tooltip. By default, the tooltip text will be blue on a white background
and with a blue border, but this can be changed. Here, I’ve set my tooltip to have white
text on a black background, and plenty of padding around the text:

marker.ToolTip.Fill = Brushes.Black;
marker.ToolTip.Foreground = Brushes.White;
marker.ToolTip.Stroke = Pens.Black;
marker.ToolTip.TextPadding = new Size(20, 20);

There is unfortunately no easy way of changing the rounded borders of the tooltip, or
add a drop shadow to it.

By default, tooltips appear when you move your mouse cursor over a marker. You can
also set a marker’s tooltip to be always visible:
marker.ToolTipMode = MarkerTooltipMode.OnMouseOver;
Marker events

It is possible to detect that a marker was clicked and do something. The markers
themselves do not have any event hooks; only the GMap.NET control itself does. To be
notified of marker clicks, implement the OnMarkerClick event (find it in the Properties
window, under Events). In the following example, I have given my markers a Tag value
so I’ll know which one was clicked, since it’s likely that in a real application my
markers will come from a database:

private void gmap_OnMarkerClick(GMapMarker item, MouseEventArgs e)


{
Console.WriteLine(String.Format("Marker {0} was clicked.",
item.Tag));
}

If you need even more interaction, you can also detect the mouse cursor hovering over a
marker (OnMarkerEnter) and leaving a marker (OnMarkerLeave).
ADDING POLYGONS AND ROUTES
TO YOUR MAP
The GMap.NET control is a popular control for .NET that allows you to put interactive
maps on your Windows Forms. In this third and last part of our GMap.NET tutorial, we
show how you can add clickable polygons and routes to your maps, and how to style
them.

Don’t forget to visit the first part of the tutorial for GMap.NET: Setting up your map
first! Also, if you landed here first, be sure to have a look at part 2: GMap.NET: Adding
markers to your map.

Adding polygons to the map

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. To add a polygon to your map, you
must define it as a list of latitude/longitude coordinates:

GMapOverlay polygons = new GMapOverlay("polygons");


List<PointLatLng> points = new List<PointLatLng>();
points.Add(new PointLatLng(48.866383, 2.323575));
points.Add(new PointLatLng(48.863868, 2.321554));
points.Add(new PointLatLng(48.861017, 2.330030));
points.Add(new PointLatLng(48.863727, 2.331918));
GMapPolygon polygon = new GMapPolygon(points, "Jardin des Tuileries");
polygons.Polygons.Add(polygon);
gmap.Overlays.Add(polygons);

The coordinates are placed in a generic list, which is then passed to the GMapPolygon
constructor. I’ve created a special overlay just for the polygons, so that I can show or
hide them all at the same time while my markers (which live in a different overlay)
remain visible. You are free to put markers, polygons and routes all in the same overlay
though.

Tip: don’t forget to add overlays to the map, or they (and the polygons in them) won’t
show up.

The polygon that appears on the map will be white with a purple border (you may have
to zoom in a little to see it). We can change these colors with the following code:

polygon.Fill = new SolidBrush(Color.FromArgb(50, Color.Red));


polygon.Stroke = new Pen(Color.Red, 1);

Here, I’ve given the polygon a red fill at at alpha = 50 (alpha ranges from 0, which is
fully transparent, to 255, which is opaque), and red line around it with a thickness of
one pixel.
Polygon events

While polygons cannot have tooltips, they can be clicked and you can intercept these
clicks. The GMapPolygon class does not support any events, but you’ll find the
OnPolygonClick event in the GMap.NET control itself (look for it in the Properties
window, under Events). Thus you can set a Tag value for your polygon and read that in
the event code, so you’ll know which polygon was clicked:

private void gmap_OnPolygonClick(GMapPolygon item, MouseEventArgs e)


{
Console.WriteLine(String.Format("Polygon {0} with tag {1} was
clicked",
item.Name, item.Tag));
}

If you need even more interaction, the GMap.NET control also has the events
OnPolygonEnter (for when the mouse cursor hovers over a polygon) and
OnPolygonLeave (for when the mouse cursor leaves a polygon) available.

Adding routes to the map

In GMap.NET, routes are very similar to polygons, only without the fill color. The
following code adds a route to the map:

GMapOverlay routes = new GMapOverlay("routes");


List<PointLatLng> points = new List<PointLatLng>();
points.Add(new PointLatLng(48.866383, 2.323575));
points.Add(new PointLatLng(48.863868, 2.321554));
points.Add(new PointLatLng(48.861017, 2.330030));
GMapRoute route = new GMapRoute(points, "A walk in the park");
route.Stroke = new Pen(Color.Red, 3);
routes.Routes.Add(route);
gmap.Overlays.Add(routes);

Note that I’ve set the route stroke color to red and given the stroke a thickness of 3, or it
would blend in with the map since the default color is purple. You may have to zoom
the map a little to see the route along the Jardin des Tuileries.

What’s special about routes is that you can have GMap.NET calculate the total route
length using the route’s Distance property. This will return the route length in
kilometers.

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;
CALCULATING THE AREA OF A
POLYGON ON THE MAP
If you’re using GMap.NET to add maps to your .NET application, then the time may
come when you want to calculate the area of a polygon on your map. In my case, I have
an application that allows users to actually create polygons using a GMap.NET control,
by placing and connecting markers to shape their polygon. Since the map system is used
to indicate the limits of an area occupied by a rural community, it’s necessary to
calculate how many hectares the delimited area occupies.

Google Maps actually provides a function in its API to calculate polygon areas:

google.maps.geometry.spherical.computeArea(yourPolygon.getPath());

Even so, unfortunately GMap.NET does not offer access to this API. Moreover, your
GMap.NET control may be configured to work with a different map provider from
Google Maps, like Bing. Consequently, you’ll have to implement your own polygon
area calculation algorithms. Luckily, this is not all that complicated, and algorithms are
available on the net.

Here’s my approach.

 Assuming that you have a list of PointLatLng values that form the polygon…
 For each PointLatLng value, create a new value with the latitude and longitude
values converted to meters.
 Calculate the area of the polygon using this algorithm.

In code:

IList<PointLatLng> coords = // List of polygon coordinates

// Add all coordinates to a list, converting them to meters:


IList<PointLatLng> points = new List<PointLatLng>();
foreach (PointLatLng coord in coords)
{
PointLatLng p = new PointLatLng(
coord.Longitude * (System.Math.PI * 6378137 / 180),
coord.Latitude * (System.Math.PI * 6378137 / 180)
);
points.Add(p);
}
// Add point 0 to the end again:
points.Add(points[0]);

// Calculate polygon area (in square meters):


var area = System.Math.Abs(points.Take(points.Count - 1)
.Select((p, i) => (points[i + 1].Lat - p.Lat) * (points[i + 1].Lng +
p.Lng))
.Sum() / 2);
GETTING RID OF THE RED CROSS
IN THE MIDDLE OF YOUR MAP
When you first slap a GMap.NET control on your Windows form, there will always be
a red cross in the middle of the map, clearly to indicate where the map center is should
your application allow people to indicate something on the map. Sometimes, though,
you’re really just showing a map and the red cross has to go.

The only catch here is that is cannot be done through the properties window of the
control, but only in code:

mymap.ShowCenter = false;
MAPS, MARKERS AND POLYGONS
The 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.

IMPORTANT: You are currently reading our old tutorial. We have a fresh
GMap.NET tutorial about maps, markers, polygons and routes that’s updated for
Visual Studio 2015 and GMap.NET 1.7!

View the updated tutorial

Note that we have more tutorials up on how to add routes to GMap.NET, calculating the
area of a polygon in GMap.NET, and removing the red cross from a map in
GMap.NET.

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

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.

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.”
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:
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:

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

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


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

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 of GMapPolygon. 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.

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

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

IMPORTANT: You are currently reading our old tutorial. We have a fresh
GMap.NET tutorial about maps, markers, polygons and routes that’s updated for
Visual Studio 2015 and GMap.NET 1.7!

View the updated tutorial

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:

PointLatLng start = new PointLatLng(-25.974134,32.593042);


PointLatLng end = new PointLatLng(-25.959048,32.592827);
MapRoute route =
GMap.NET.MapProviders.GoogleMapProvider.Instance.GetRoute(
start, end, false, false, 15);

or

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

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 GetRoutemethod 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?”

GMapRoute r = new GMapRoute(route.Points, "My route");

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:

GMapOverlay routesOverlay = new GMapOverlay("routes");


routesOverlay.Routes.Add(r);
gmap.Overlays.Add(routesOverlay);

The result should be:


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:

r.Stroke.Width = 2;
r.Stroke.Color = Color.SeaGreen;
API Google Maps: cómo conseguir una
API Key en 10 minutos
Hay días que me levanto muy muy Millenial y pienso ¿Cómo narices me movía por el mundo
cuando no existía Google Maps? De verdad, que me imagino de viaje con mi mapa de papel o
intentando orientarme para llegar a un sitio un poco escondido y no me veo.

De entre todas las utilidades maravillosas de Google Maps, hay una especialmente
poderosa y bastante poco conocida fuera del sector más técnico o de desarrollo web: la
API de Google Maps.

En las últimas semanas he hablado varias veces de esta herramienta de Google y,


como siempre me pasa últimamente, he aprovechado para juntar esa información y
escribir este post. ¡Espero que te resulte útil!

Para el caso de Google Maps, su API ofrece una serie de funciones que permiten a los
programadores integrar los servicios de Google en sus desarrollos webs (o aplicaciones
móviles) de manera más o menos sencilla, sin tener que volver a programar todas las
funcionalidades de Google Maps ni tampoco tener que conocer cómo lo han programado.

Podríamos decir que una API es una especie de «traductor» que se encarga de
transformar las peticiones de un desarrollo informático a otro lenguaje o sistema y
después devolver el resultado como respuesta.

¿Para qué sirve la API de mapas?

La API de Google Maps se incluye dentro del servicio de Google Maps Platform y
engloba realmente muchas APIs individuales para los distintos servicios o
funcionalidades que ofrece.

Desde las APIs se pueden generar mapas con estilos personalizados, crear rutas a
partir del tráfico o consultar las imágenes de Google Earth o Street View, entre
otras muchas cosas.
Correcto, hay más opciones de las que pensabas en Google Maps

Aunque lleva existiendo mucho tiempo, en los últimos meses se ha escuchado/leído


muchísimo más sobre las APIs de Google Maps. ¿Por qué? Sencillamente porque en
2017 Google pasó a obligar usar una clave privada para usar los servicios de su API. Y
después, en 2018, decidió hacer la API de pago para cierto tipo de peticiones fuera
de los mapas estándar.

Esto supuso un caos bastante grande para aquellas apps que giraban mucho alrededor de
los mapas de Google y que iban a tener que empezar a pagar por su uso. Pero más
adelante hablamos del tema de pago, que me lío. Si quieres, puedes echarle un ojo a este
post de elandroidelibre donde hablaban del tema.

Si tienes una web en WordPress es posible que hayas necesitado generar esa API Key.
O directamente has optado por otros métodos para incrustar tus mapas. Algunas
plantillas como Divi, utilizan la API de Google Maps para mostrar los mapas y
necesitan que le pongas la clave para que no dé error:
Módulo Mapas para Divi

¿Se puede usar Google Maps sin la API?

Respuesta corta: sí, se puede tener un mapa de Google Maps en tu web sin pasar
por caja. Al menos de momento.

Los mapas generados con el código de «embed» desde la web de Google Maps de
momento no hacen uso de la API y no necesitan de claves ni pagos. Hace unos meses te
contábamos cómo insertar un mapa de Google Maps en este mismo blog.

¿Cómo conseguir una API Key de G.Maps? [actualizado 2018]

A raíz de los últimos cambios en la plataforma de Google que hemos comentado, el


método para conseguir generar la clave de la API de Google Maps (API key en
inglés y la mayoría de plugins y themes de WordPress) ha cambiado ligeramente y
es un poco lioso.

Pero voy a intentar ponerlo fácil y paso a paso.

Registro en Google Cloud Platform

El primer paso es acceder a Google Cloud Platform, la plataforma de Google en la


nube que también sirve de centro para G Suite, del que ya os hemos hablado antes por
aquí también.
Para acceder, podemos ir a https://cloud.google.com/ y entrar con nuestra de Google
(una de G Suite o una de Gmail es suficiente) o entrar directamente (más fácil) a este
enlace que nos lleva directo al acceso de Maps. Te encontrarás algo así:

Primeros pasos en Google Cloud Platform para Maps

Si no se abre directamente esta ventana, haz clic en el botón de «Primeros pasos» de


la esquina superior derecha.

En esa primera ventana, debemos marcar qué APIs queremos utilizar. Aquí ya
depende de tu aplicación y lo que necesites, pero lo habitual es que solo marques la de
Maps (se puede cambiar después, no sufras)

Crear un proyecto

Si no estamos logados aún, nos pedirá entrar en nuestra cuenta de Google antes de
continuar al siguiente paso. Este es fácil: usuario y contraseña de Gmail y a correr.

Seguramente nos toque repetir el punto anterior. Otra vez clic en primeros pasos, y
marcamos las APIs que queramos usar.

Ahora toca crear un proyecto. Google Cloud Platform se mueve por proyectos, y
cada proyecto tiene sus accesos a APis y sus estadísticas. Es un poco rollo, pero es
mucho más eficiente para tener todo controlado cuando tienes varios proyectos en
paralelo.
Creando el proyecto

Es sencillo, ponemos nombre al proyecto (Por ejemplo, «mapas Web corporativa» o lo


que quieras) y aceptamos las condiciones de servicio

Configurar método de pago

Una vez tengamos el proyecto, lo siguiente que nos pedirá es configurar es el método de
pago. Sí, esta es una de las últimas «trabas» que pusieron: es imprescindible meter el
método de pago antes de generar la API Key. Esto en la práctica puede ser un drama
si tenemos un pico de visitas descomunal, por lo que tienes que tener claro cuál será tu
tráfico y qué costes podría suponer. Pero hablamos de los precios más adelante.
Debemos habilitar la facturación antes

El proceso para crear la cuenta de facturación es bastante sencillo. Simplemente rellena


tus datos y lo tendrás todo listo.

Me hace gracia que nos pidan la tarjeta de crédito para comprobar que no somos un
robot… ¡antes usábamos captchas para eso!
Habilitar API y generar API Key

Una vez tengamos asociada la forma de pago, volveremos al proceso de activar las
APIs de Google Maps. Nos encontraremos un mensaje de este estilo:

Después de darle a continuar, se quedará un rato pensando y terminará por generar,


por fin, la deseada API KEY que necesitábamos.

(Sí, aquí debería ir otra captura, pero soy un poco tonto y he cerrado la ventana sin
querer… no me lo tengáis mucho en cuenta)

Ya solo tienes que copiarla y pegarla en la plataforma/web/plugin/theme que


necesitabas y comprobar que todo funciona correcto. O para enviársela a tu
desarrollador para que integre la APIs correctamente.

Extra de seguridad: asociar tu página web a la API Key

Para evitar sustos (y disgustos) en la facturación, una buena medida de seguridad es


restringir el proyecto y la API Key únicamente a tu web (o webs o apps) que tú
administres.

En esa propia de Google, tenemos un enlace hacia la «API Console» desde donde
podemos gestionar esto.

Desde aquí podremos generar una nueva API, cambiarle el nombre para
identificarla mejor y, lo más interesante de todo, establecer restricciones de uso.
Lo habitual es marcar la opción «URLs de referencia HTTP (sitios web)» y en el cuadro
que aparecerá después, incluir nuestra web.

Consejo: rellena con https://tudominio.com si los mapas están en la home de tu web y con
https://tudominio.com/* si están en cualquier otra página interior. De lo contrario, es posible
que te dé error.

Ahora sí que sí. ¡Listo! Ya podemos utilizar la API Key de Google Maps y ser un
poquito más felices… hasta que hablemos del pago/precio de la herramienta.
¿Cuánto cuesta la API de Google Maps?

Os voy a ser 100% sincero: no consigo aclararme con los pagos de Google Maps.
Tengo claro dos cosas:

 Al registrarte en el sistema tienes 200$ mensuales de crédito gratis.


 Ese crédito debería ser suficiente para cubrir necesidades básicas de tu web.

En la práctica, en Ensalza tenemos varias webs de clientes (corporativas, con poquito


tráfico) y todavía no hemos llegado a cubrir ni el 60% de los créditos gratuitos mes a
mes. Así que debe cundir bastante.

Para resolver todas tus dudas sobre esto (y porque sospecho que lo van a ir
cambiando en los próximos meses), te invito a que le eches un ojo a la propia
página de precios de Google Maps y a la calculadora de precios que han desarrollado
en Google.

Bueno, pues hasta aquí el artículo de hoy ¿os ha resultado sencillo el proceso? ¿habéis
necesitado usar la API de Google Maps en algún momento?

You might also like