Click here to Skip to main content
15,881,685 members
Articles / Web Development / HTML
Tip/Trick

C# - Google Maps in WinForm with WebBrowser and Google Maps API v3

Rate me:
Please Sign up or sign in to vote.
4.95/5 (12 votes)
24 Mar 2015CPOL 126.6K   18.1K   36   10
With this tip, you can show a map in your WinForm application with the Google Maps API v3.

Introduction

Google provides a JavaScript API for including maps with the same functions of maps.google.com in an HTML page.

In version v2, you need to register to obtain an API key for using the library, with version v3 it's optional but it's recommended because the API has a limitation, you can only generate 25,000 maps per day, if you need more you need to pay so you need to register and if you register you can:

  • Obtain statistics of the maps generated per day
  • Pay for additional maps (more than 25,000 per day)
  • Restrict the use of your key to prevent use on unauthorized sites

Before Coding

1. Create the Locations database

Image 1

2. Create the HTML5 Template and use GoogleMaps Script
HTML
<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>My Map</title>
</head>
<body>
    <style>
        * {
            margin: 0;
        }

        body, html {
            height: 100%;
            width: 100%;
        }

        .map-canvas {
            width: 100%;
            height: 100%;
        }
    </style>
    <div id="map-canvas" class="map-canvas">
    </div>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
    <script type="text/javascript">
        var map;
        function initialize() {
            //CADM GEO-INFO
            var CDAM_Latlng = new google.maps.LatLng([la], [lo]);
            var CDAM_mapOptions = {
                zoom: 6,
                center: CDAM_Latlng
            }

            // the map :
            var map = new google.maps.Map(document.getElementById('map-canvas'), CDAM_mapOptions);
            google.maps.event.trigger(map, 'resize');
            //markers icon :
            var iconHome = "[marker]";
            var otherpart = "[marker]";

            //set markers :
            var CDAM_marker = new google.maps.Marker({
                animation: google.maps.Animation.DROP,
                position: CDAM_Latlng,
                map: map,
                title: '[country]',
                icon: iconHome
            });

            // info_window content_string
            var CDAM_infoContent = '<div id="content" style="margin:0 auto;">' +
                                '<center><img src="[image]" />' +
                                '<h3>[country]</h3><h6>[city]</h6></center>' +
                                '</div>';

            // info window CDAM:
            var infowindowCDAM = new google.maps.InfoWindow({
                content: CDAM_infoContent
            });

            //Event Listener :

            //CDAM info window :
            google.maps.event.addListener(CDAM_marker, 'mouseover', function () {
                infowindowCDAM.open(map, CDAM_marker);
            });

            google.maps.event.addListener(CDAM_marker, 'mouseout', function () {
                infowindowCDAM.close(map, CDAM_marker);
            });

            //Effect Click :
            google.maps.event.addListener(CDAM_marker, 'click', function toggleBounce() {
                if (CDAM_marker.getAnimation() != null) {
                    CDAM_marker.setAnimation(null);
                } else {
                    CDAM_marker.setAnimation(google.maps.Animation.BOUNCE);
                }
            });

        }
        // apply domListener :
        google.maps.event.addDomListener(window, 'load', initialize);

    </script>
</body>
</html>

3. Create you WinForm Application

Image 2

Use the Code

1. Create the "Provider" Class
C#
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace GoogleMaps_Application
{
    [Serializable]
    class Provider
    {
        /*Data item*/
        private string cs = @"Data Source=.; initial catalog = locations ; integrated security = true";
        private string query = null;
        private SqlConnection cn = null;
        private SqlCommand cm = null;
        private SqlDataReader dr = null;
        private DataTable dt = null;

        /*set value to null*/
        private void Initial()
        {
            query = null;
            cn = null;
            cm = null;
            dr = null;
            dt = null;
        }

        /*load data from database*/
        public DataTable Load(string table)
        {
            DataTable d = null;
            try
            {
                cn = new SqlConnection(cs);
                query = "select * from " + table;
                cm = new SqlCommand(query, cn);
                dt = new DataTable();
                cn.Open();
                dr = cm.ExecuteReader();
                dt.Load(dr);
                cn.Close();
                d = dt;
                Initial();
                return d;
            }
            catch (Exception x)
            {
                MessageBox.Show(x.Message);
                return dt;
            }
        }

        public DataTable Loading(string query)
        {
            DataTable d = null;
            try
            {
                cn = new SqlConnection(cs);
                cm = new SqlCommand(query, cn);
                dt = new DataTable();
                cn.Open();
                dr = cm.ExecuteReader();
                dt.Load(dr);
                cn.Close();
                d = dt;
                Initial();
                return d;
            }
            catch (Exception x)
            {
                MessageBox.Show(x.Message);
                return dt;
            }
        }
    }
}
2. Create The "Variables" Class to update your HTML5 template
C#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace GoogleMaps_Application
{
    class variables
    {
        public static void replace(string filename,string la,string lo,
        	string country,string city,string marker,string image,string path)
        {
            if(File.Exists(filename))
            {
                StreamReader reader = new StreamReader(filename);
                string readFile = reader.ReadToEnd();
                string sb = "";
                sb = readFile;
                sb = sb.Replace("[la]", la);
                sb = sb.Replace("[lo]", lo);
                sb = sb.Replace("[country]", country);
                sb = sb.Replace("[city]", city);
                sb = sb.Replace("[image]", image);
                sb = sb.Replace("[marker]", marker);

                readFile = sb.ToString();
                reader.Close();
                StreamWriter writer = new StreamWriter(path);
                writer.Write(readFile);
                writer.Close();

                writer = null;
                reader = null;
            }
            else
                System.Windows.Forms.MessageBox.Show("Im Sorry About That !");
        }
    }
}
3. Create Methods and delegates to update your template and to show the result in WebBrowser
C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace GoogleMaps_Application
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        DataTable countries;
        DataTable cities;
        TreeNode Node, subNode;
        public delegate void Add(TreeNode i);

        public delegate void performeSteps(int value);
        public void performeStep(int value)
        {
            //status progress bar  :
            pb_state.Value = value;
            //status label  :
            lbl_state.Text = value + "%";
        }

        void LoadData()
        {
            try
            {
                countries = new Provider().Load("countries");
                int count = countries.Rows.Count, current = 0;
                foreach (DataRow country in countries.Rows)
                {
                    Node = new TreeNode(country["english"].ToString());
                    cities = new Provider().Loading(string.Format
                    	("select city from cities where country_id = {0}",
                                    int.Parse(country["ID"].ToString())));
                    foreach (DataRow city in cities.Rows)
                    {
                        subNode = new TreeNode(city["city"].ToString());
                        Node.Nodes.Add(subNode);
                        Node.ImageIndex = 0;
                        subNode.ImageIndex = 1;
                    }
                    treeView1.Invoke(new Add(Add1), new object[] { Node });
                    current++;
                    Strip_State.Invoke(new performeSteps(performeStep), 
				new object[] { (current * 100) / count });
                }
                treeView1.NodeMouseClick += new TreeNodeMouseClickEventHandler(TreeClick);
                treeView1.Update();
                countries = null;
                cities = null;

            }
            catch (Exception x)
            {
                string h = x.Message;
            }
        }

        public void Add1(TreeNode i)
        {
            treeView1.Nodes.Add(i);
        }

        public void TreeClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            DataTable dt = new Provider().Loading("select c.lat , c.lon , co.english , 
						c.city from cities as c " +
                                                  "inner join countries as co " +
                                                  "on c.country_id = co.id " +
                                                    "and c.city = '" + e.Node.Text + "'");
            if (dt.Rows.Count > 0)
            {
                string marker = "marker.png";
                string image = "image.png";
                string path = Application.StartupPath + "\\map.html";
                this.Text = path;
                string filename = Application.StartupPath + "\\mymap.html";
                DataRow r = dt.Rows[0];
                variables.replace(filename, r["lat"].ToString(), r["lon"].ToString(),
                                    r["english"].ToString(), r["city"].ToString(),
                                    marker, image, path);
                this.webBrowser1.Url = new Uri(path);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            if (!BKProgress.IsBusy)
                BKProgress.RunWorkerAsync();
        }

        private void BKProgress_DoWork(object sender, DoWorkEventArgs e)
        {
            LoadData();
        }

        private void BKProgress_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            lbl_state.Text = "Done!";
        }
    }
}

Results

Image 3

Image 4

Image 5

C#
If(You_Like_This_Article())
   ShareItNow();
// thank you ;)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
SMPS
Morocco Morocco
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionGot script error Pin
MrBjorn12-Aug-20 23:18
MrBjorn12-Aug-20 23:18 
BugWhen clicking on Country name no state name being display and no map drawn Pin
svdevendra16-Jun-20 20:03
svdevendra16-Jun-20 20:03 
QuestionHow To set browser Pin
Sushil.Agarwal3-Apr-18 21:30
Sushil.Agarwal3-Apr-18 21:30 
QuestionHelp Pin
Uno Dos14-Nov-17 1:17
Uno Dos14-Nov-17 1:17 
Questionwhere is database ?? Pin
rizwankhan00721-Mar-16 15:26
rizwankhan00721-Mar-16 15:26 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun27-Mar-15 2:53
Humayun Kabir Mamun27-Mar-15 2:53 
GeneralGood Tutorial Pin
Member 1110549025-Mar-15 17:47
Member 1110549025-Mar-15 17:47 
GeneralMy vote of 5 Pin
loyal ginger25-Mar-15 2:07
loyal ginger25-Mar-15 2:07 
QuestionImages Pin
Andre Greyling24-Mar-15 20:13
Andre Greyling24-Mar-15 20:13 
Questionwhere is the database? Pin
Member 1030960424-Mar-15 10:59
Member 1030960424-Mar-15 10:59 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.