Click here to Skip to main content
15,892,575 members
Articles / Programming Languages / Visual Basic

Integrating MapPoint in your .NET applications

Rate me:
Please Sign up or sign in to vote.
4.93/5 (16 votes)
2 Oct 20056 min read 140.2K   1.6K   67  
Using the MapPoint web service API and C# to calculate the route/driving directions between two places (e.g. cities) and generate a map showing the same.
using System;
using System.ComponentModel;
using System.Configuration;
using System.Drawing;
using System.IO;
using System.Net;
using System.Windows.Forms;
using MapPoint_Demo.MapPoint;

namespace MapPoint_Demo
{
	/// <summary>
	/// Summary description for Form1.
	/// </summary>
	public class Form1 : Form
	{
		private TabControl tbMain;
		private StatusBar stsMain;
		private TextBox txtResults;
		private TextBox txtOrigAddress;
		private TextBox txtDestAddress;
		private Button btnDirections;
		private Label lblOrigAddress;
		private Label lblDestAddress;
		private TabPage tpMain;
		private TabPage tpMap;
		private PictureBox pcMap;
		private System.Windows.Forms.ComboBox cmbZone;
		private System.Windows.Forms.Label lblZone;
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private Container components = null;

		public Form1()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.tbMain = new System.Windows.Forms.TabControl();
			this.tpMain = new System.Windows.Forms.TabPage();
			this.lblZone = new System.Windows.Forms.Label();
			this.cmbZone = new System.Windows.Forms.ComboBox();
			this.txtResults = new System.Windows.Forms.TextBox();
			this.lblDestAddress = new System.Windows.Forms.Label();
			this.lblOrigAddress = new System.Windows.Forms.Label();
			this.btnDirections = new System.Windows.Forms.Button();
			this.txtDestAddress = new System.Windows.Forms.TextBox();
			this.txtOrigAddress = new System.Windows.Forms.TextBox();
			this.tpMap = new System.Windows.Forms.TabPage();
			this.pcMap = new System.Windows.Forms.PictureBox();
			this.stsMain = new System.Windows.Forms.StatusBar();
			this.tbMain.SuspendLayout();
			this.tpMain.SuspendLayout();
			this.tpMap.SuspendLayout();
			this.SuspendLayout();
			// 
			// tbMain
			// 
			this.tbMain.Controls.Add(this.tpMain);
			this.tbMain.Controls.Add(this.tpMap);
			this.tbMain.Location = new System.Drawing.Point(8, 8);
			this.tbMain.Name = "tbMain";
			this.tbMain.SelectedIndex = 0;
			this.tbMain.Size = new System.Drawing.Size(376, 304);
			this.tbMain.TabIndex = 0;
			// 
			// tpMain
			// 
			this.tpMain.Controls.Add(this.lblZone);
			this.tpMain.Controls.Add(this.cmbZone);
			this.tpMain.Controls.Add(this.txtResults);
			this.tpMain.Controls.Add(this.lblDestAddress);
			this.tpMain.Controls.Add(this.lblOrigAddress);
			this.tpMain.Controls.Add(this.btnDirections);
			this.tpMain.Controls.Add(this.txtDestAddress);
			this.tpMain.Controls.Add(this.txtOrigAddress);
			this.tpMain.Location = new System.Drawing.Point(4, 22);
			this.tpMain.Name = "tpMain";
			this.tpMain.Size = new System.Drawing.Size(368, 278);
			this.tpMain.TabIndex = 0;
			this.tpMain.Text = "Directions";
			// 
			// lblZone
			// 
			this.lblZone.Location = new System.Drawing.Point(50, 16);
			this.lblZone.Name = "lblZone";
			this.lblZone.TabIndex = 7;
			this.lblZone.Text = "Zone";
			// 
			// cmbZone
			// 
			this.cmbZone.Items.AddRange(new object[] {
														 "MapPoint.NA",
														 "MapPoint.EU"});
			this.cmbZone.Location = new System.Drawing.Point(176, 16);
			this.cmbZone.Name = "cmbZone";
			this.cmbZone.Size = new System.Drawing.Size(121, 21);
			this.cmbZone.TabIndex = 6;
			this.cmbZone.Text = "MapPoint.NA";
			// 
			// txtResults
			// 
			this.txtResults.Location = new System.Drawing.Point(8, 160);
			this.txtResults.Multiline = true;
			this.txtResults.Name = "txtResults";
			this.txtResults.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
			this.txtResults.Size = new System.Drawing.Size(352, 104);
			this.txtResults.TabIndex = 5;
			this.txtResults.Text = "";
			// 
			// lblDestAddress
			// 
			this.lblDestAddress.Location = new System.Drawing.Point(48, 80);
			this.lblDestAddress.Name = "lblDestAddress";
			this.lblDestAddress.Size = new System.Drawing.Size(112, 23);
			this.lblDestAddress.TabIndex = 4;
			this.lblDestAddress.Text = "Destination Address";
			// 
			// lblOrigAddress
			// 
			this.lblOrigAddress.Location = new System.Drawing.Point(48, 48);
			this.lblOrigAddress.Name = "lblOrigAddress";
			this.lblOrigAddress.Size = new System.Drawing.Size(104, 23);
			this.lblOrigAddress.TabIndex = 3;
			this.lblOrigAddress.Text = "Origin Address";
			// 
			// btnDirections
			// 
			this.btnDirections.Location = new System.Drawing.Point(136, 120);
			this.btnDirections.Name = "btnDirections";
			this.btnDirections.Size = new System.Drawing.Size(88, 23);
			this.btnDirections.TabIndex = 2;
			this.btnDirections.Text = "Get Directions";
			this.btnDirections.Click += new System.EventHandler(this.btnDirections_Click);
			// 
			// txtDestAddress
			// 
			this.txtDestAddress.Location = new System.Drawing.Point(176, 80);
			this.txtDestAddress.Name = "txtDestAddress";
			this.txtDestAddress.Size = new System.Drawing.Size(168, 20);
			this.txtDestAddress.TabIndex = 1;
			this.txtDestAddress.Text = "";
			// 
			// txtOrigAddress
			// 
			this.txtOrigAddress.Location = new System.Drawing.Point(176, 48);
			this.txtOrigAddress.Name = "txtOrigAddress";
			this.txtOrigAddress.Size = new System.Drawing.Size(168, 20);
			this.txtOrigAddress.TabIndex = 0;
			this.txtOrigAddress.Text = "";
			// 
			// tpMap
			// 
			this.tpMap.Controls.Add(this.pcMap);
			this.tpMap.Location = new System.Drawing.Point(4, 22);
			this.tpMap.Name = "tpMap";
			this.tpMap.Size = new System.Drawing.Size(368, 278);
			this.tpMap.TabIndex = 1;
			this.tpMap.Text = "Map";
			// 
			// pcMap
			// 
			this.pcMap.Location = new System.Drawing.Point(8, 8);
			this.pcMap.Name = "pcMap";
			this.pcMap.Size = new System.Drawing.Size(352, 256);
			this.pcMap.TabIndex = 0;
			this.pcMap.TabStop = false;
			// 
			// stsMain
			// 
			this.stsMain.Location = new System.Drawing.Point(0, 311);
			this.stsMain.Name = "stsMain";
			this.stsMain.Size = new System.Drawing.Size(392, 22);
			this.stsMain.TabIndex = 1;
			// 
			// Form1
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(392, 333);
			this.Controls.Add(this.stsMain);
			this.Controls.Add(this.tbMain);
			this.Name = "Form1";
			this.Text = "MapPoint: Route Planner";
			this.Load += new System.EventHandler(this.Form1_Load);
			this.tbMain.ResumeLayout(false);
			this.tpMain.ResumeLayout(false);
			this.tpMap.ResumeLayout(false);
			this.ResumeLayout(false);

		}
		#endregion

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main() 
		{
			Application.Run(new Form1());
		}


		//Set up the service variables, get application 
		//settings from the App.config file
		//myCredentials holds the network credentials for MapPoint account
		static string myUserID = ConfigurationSettings.AppSettings.Get("MPUser");
		static string myPassword = ConfigurationSettings.AppSettings.Get("MPPass");
		NetworkCredential myCredentials = new NetworkCredential(myUserID, myPassword);
        
		//RenderServiceSoap is useful in working with maps
		RenderServiceSoap renderService = new RenderServiceSoap();
		
		//FindServiceSoap is useful in finding addresses and related information
		FindServiceSoap findService = new FindServiceSoap();

		private void Form1_Load(object sender, EventArgs e)
		{
			try
			{
//			//For users who are behind a internet proxy
//			//Comment out for direct internet connection
//			WebProxy myProxy = new WebProxy("http://proxyip:80",true);
//			myProxy.Credentials = new NetworkCredential("username", "password", "domain");
		
			//Passing the MapPoint account credentials to the proper service
			renderService.Credentials = myCredentials;
			renderService.PreAuthenticate = true;
//			renderService.Proxy = myProxy;	
		
			findService.Credentials = myCredentials;
			findService.PreAuthenticate = true;
//			findService.Proxy = myProxy;
		 }           
        catch
			{
				
			}  
		}

		private void btnDirections_Click(object sender, EventArgs e)
		{
			//Resets the textbox text and the statusbar text
			txtResults.Text = string.Empty;
			stsMain.Text = string.Empty;
			
			FindSpecification findSpec = new FindSpecification();
			
			FindResults startResults = null;
            FindResults endResults = null;
			
			//Set the DataSource, i.e. MapPoint.EU for Europe etc.
			findSpec.DataSourceName = cmbZone.Text;
			
			findSpec.InputPlace = txtOrigAddress.Text;
			
			//Retrieve the values of startResults
			try
			{
				startResults = findService.Find(findSpec);
			}
			catch
			{
				MessageBox.Show("Problem connecting with service");
			}
			
			
			findSpec.InputPlace = txtDestAddress.Text;
			
			//Retrieve the values of endResults
			try
			{
				endResults = findService.Find(findSpec);
			}
			catch
			{
				MessageBox.Show("Problem connecting with service");
			}


			// Make sure findResults isn't null
			if(startResults == null)
			{
				MessageBox.Show("Originating Address not found.");
			}
			else
			{
				// If no results were found, display error and return
				if(startResults.NumberFound == 0)
				{
					MessageBox.Show("Originating Address not found.");
					return;
				}
				
			}
			if(endResults == null)
			{
				MessageBox.Show("Destination Address not found.");
			}
			else
			{
				// If no results were found, display error and return
				if(endResults.NumberFound == 0)
				{
					MessageBox.Show("Destination Address not found.");
					return;
				}
			}

			stsMain.Text = "Generating Route Information";

			//Call GetRoute:Calculates the Route and also generates the Map
			GetRoute(startResults,endResults);
		}
        
		
		//GetRoute:Calculates the Route and also generates the Map
		private void GetRoute(FindResults sResults,FindResults eResults)
		{
			SegmentSpecification[] routeSegment;
			routeSegment = new SegmentSpecification[2];

			routeSegment[0]= new SegmentSpecification();
            routeSegment[0].Waypoint = new Waypoint();
            routeSegment[0].Waypoint.Name = sResults.Results[0].FoundLocation.Entity.Name;
			routeSegment[0].Waypoint.Location = sResults.Results[0].FoundLocation;

		    routeSegment[1]= new SegmentSpecification();
			routeSegment[1].Waypoint = new Waypoint();
			routeSegment[1].Waypoint.Name = eResults.Results[0].FoundLocation.Entity.Name;
			routeSegment[1].Waypoint.Location = eResults.Results[0].FoundLocation;
		

            RouteSpecification routeSpecs = new RouteSpecification();
            routeSpecs.DataSourceName = cmbZone.Text;
			routeSpecs.Segments = routeSegment;

//			//For users who are behind a internet proxy
//			//Comment out for direct internet connection
//			WebProxy myProxy = new WebProxy("http://proxyip:80",true);
//			myProxy.Credentials = new NetworkCredential("username", "password", "domain");
//		
			RouteServiceSoap routeService = new RouteServiceSoap();
			routeService.Credentials = myCredentials;
			routeService.PreAuthenticate = true;
//			routeService.Proxy = myProxy;

			Route route = new Route();
            route = routeService.CalculateRoute(routeSpecs);

            stsMain.Text = "Fetching Route Information";
            
			//loop through and write the route directions in the textbox
			for (int i = 0;i < route.Itinerary.Segments[0].Directions.Length;i++ )
			{
				txtResults.Text +="("+(i+1)+") "+route.Itinerary.Segments[0].Directions[i].Instruction +" >> ";
			}
           
			stsMain.Text = "Wait...Generating Map Information";

            // Generate the Route Map
			MapSpecification mapSpec = new MapSpecification();
			mapSpec.Options = new MapOptions();
			mapSpec.Options.Format = new ImageFormat();

			//Set the map width and height according to the PictureBox
			mapSpec.Options.Format.Height = pcMap.Height;
			mapSpec.Options.Format.Width = pcMap.Width;

			//Set the Map Datasource
			mapSpec.DataSourceName = cmbZone.Text;
            
			mapSpec.Route = route;
		
			
			try
			{
			// Get the map image
			MapImage tempImage = renderService.GetMap(mapSpec)[0];
			pcMap.Image = 
				new Bitmap(new MemoryStream(tempImage.MimeData.Bits, false), true);
			
			stsMain.Text = "Done";
			}
			catch(Exception e)
			{
				MessageBox.Show(e.ToString());
			}
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
India India
Chayan Ray has been working as a Technical Consultant in a CMM level 5 company in India. His technical domain includes ASP.NET, C#, PHP, Perl, Cold Fusion, MySQL and MSSQL 2000.

Comments and Discussions